package com.test.util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
public class HttpPostUploadUtil {
/**
* @param args
*/
public static void main(String[] args) {
String filePath = "D:\\Test\\0.jpg";
String url = "http://127.0.0.1:8080/FastFds";
//调用上传方法
String backInfo = uploadPost(url, filePath);
if(StringUtils.isNotBlank(backInfo)){
//转json数据
JSONObject json = JSONObject.fromObject(backInfo);
if(!json.isEmpty()){
//数据处理
String value = json.getString("test");
System.out.println(value);
}
}
}
/**
* 上传图片/文件
* @param url
* @param filePath
* @return String 用于转json或者其他信息
*/
public static String uploadPost(String url, String filePath) {
String requestJson = "";
//传入参数可以为file或者filePath,在此处做转换
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置浏览器兼容模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//添加文件
builder.addBinaryBody("file", file);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
httpResponse = httpClient.execute(httppost);
int backCode = httpResponse.getStatusLine().getStatusCode();
if(backCode == HttpStatus.SC_OK){
HttpEntity httpEntity = httpResponse.getEntity();
byte[] json= EntityUtils.toByteArray(httpEntity);
requestJson = new String(json, "UTF-8");
//关闭流
EntityUtils.consume(httpEntity);
return requestJson;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源
try {
httpClient.close();
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}