java post 发送数据并且拿到服务器返回的参数
最近用了很多post发送数据,就想着把这个记录一下
废话不多说,这个是发送数据的。
/**post 发送作业数据*/
public static void doPost(String data,String url) {
//创建httpclient对象
try{
CloseableHttpClient client = HttpClients.createDefault();
//创建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 = client.execute(httpPost);
// 检验返回码
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != 200){
httpPost.abort();
httpPost.releaseConnection();
}else {
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
String string = changeInputStream(stream, "utf-8");
System.out.println(string + "-----------");
}
httpPost.releaseConnection();
}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 = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
//将字节转换为字符串
result = new String(outputStream.toByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}