package com.sincere.student.utils; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; 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.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; /** * HttpClient4.3工具类 * @author chen * @version 1.0 * @date 2019/10/11 0011 10:17 */ public class HttpClientUtils { private static RequestConfig requestConfig = null; static { // 设置请求和传输超时时间 requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); } public static void main(String[] args){ // String url = "http://http://zhktest.114school.com.cn/szkjapi/toyxy/addTeacherOrg" ; // String json = "{\"name\": \"子部门\",\"groupname\": \"父部门\",\"schoolid\": \"16\",\"token\": \"05719991\"}" ; // JSONObject jsonObject = HttpClientUtils.httpPostJson(url,json); // System.out.println(jsonObject.toJSONString()); } public static String upload(String url, File file, String filename) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build(); httppost.setConfig(requestConfig); FileBody bin = new FileBody(file); StringBody comment = new StringBody(filename, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("filename", comment).build(); httppost.setEntity(reqEntity); httppost.setHeader("ossPath","test"); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseEntityStr = EntityUtils.toString(response.getEntity()); System.out.println(responseEntityStr); return responseEntityStr ; } EntityUtils.consume(resEntity); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null ; } }