javapost发送请求并获取返回值java post 发送数据并且拿到服务器返回的参数
最近⽤了很多post发送数据,就想着把这个记录⼀下
废话不多说,这个是发送数据的。
/**post 发送作业数据*/
public static  void doPost(String data,String url) {write的返回值
//创建httpclient对象
try{
CloseableHttpClient client = ateDefault();
//创建post⽅式请求对象
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("imageBase64",data));
//url格式编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
httpPost.setEntity(uefEntity);
CloseableHttpResponse response = ute(httpPost);
// 检验返回码
int statusCode = StatusLine().getStatusCode();
if(statusCode != 200){
httpPost.abort();
}else {
HttpEntity entity = Entity();
InputStream stream = Content();
String string = changeInputStream(stream, "utf-8");
System.out.println(string + "-----------");
}
}catch (IOException io){
io.printStackTrace();
System.out.println(io + "send homeworkJson error");
}
}
这个是接收返回参数的
// 将输⼊流按照编码格式读取为字符
private static String changeInputStream(InputStream inputStream,  String encode) {
//创建字节流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result=null;
if (inputStream != null) {
try {
while ((len = ad(data)) != -1) {
outputStream.write(data, 0, len);
}
//将字节转换为字符串
result = new ByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。