1. 在pom文件中引入相关jar
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
2. 创建HttpClientRequestUtil工具类
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClientRequestUtil {
private static final HttpClient client = HttpClientBuilder.create().build();
public static String doPost(List<NameValuePair> urlParameters,String URL) {
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(URL);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
.setSocketTimeout(3000).setConnectionRequestTimeout(3000)
.setRedirectsEnabled(true).build();
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(urlParameters, "UTF-8");
httppost.setEntity(uefEntity);
httppost.setConfig(requestConfig);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200){
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
System.out.println("--------------------------------------");
System.out.println("Response content: " +result);
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
}else {
System.out.println("******************************************请求失败+++++++++++++++++++++++++++++====");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doGet(String URL) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String doPostJson(String jsonStr,String URL) throws Exception {
StringEntity sEntity = new StringEntity(JSONObject.fromObject(jsonStr).toString(), "utf-8");
sEntity.setContentType("application/json");
HttpPost post = new HttpPost(URL);
post.setEntity(sEntity);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
public static Map<String, String> doPostFile(String url, List<MultipartFile> multipartFiles,String fileParName,
Map<String, Object> params, int timeout) {
Map<String, String> resultMap = new HashMap<String, String>();
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = null;
MultipartFile multipartFile = null;
for (int i = 0; i < multipartFiles.size(); i++) {
multipartFile = multipartFiles.get(i);
fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
}
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null)
continue;
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);
HttpEntity responseEntity = response.getEntity();
resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
resultMap.put("data", "");
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
resultMap.put("data", result);
}
} catch (Exception e) {
resultMap.put("scode", "error");
resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());
Writer w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
}
}
3. 业务实现类调用Demo
public String uploadFilesToYB(List<MultipartFile> multipartFiles) {
String ticket = this.getRedisTicket();
String postUrl = YBZLURL+"/file/upload_file";
Map<String ,Object> map=new HashMap<>();
map.put("system_id", YBZLSYSID);
map.put("ticket", ticket);
Map<String, String> resultDataMap = HttpClientRequestUtil.doPostFile(postUrl,multipartFiles,"files",map,-1);
String jsonStr = resultDataMap.get("data");
if (StringUtils.isNotEmpty(jsonStr)){
ResultJson js = (ResultJson)FastJsonTools.jsonStringToBean(jsonStr,ResultJson.class);
if (js.getCode()==200){
Map<String,String> rsMap = FastJsonTools.jsonStringToMap(js.getInfo());
String ordersJson = JSONObject.toJSONString(rsMap.get("file_list"));
return ordersJson;
}
}
return jsonStr;
}