工做以來接觸的都是spring項目,推薦使用RestTemplate!
java
package cn.sipaote.human.utils; import java.util.Map; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; /** * @description: * @author: yangshuai * @create: 2020-05-26 10:20 **/ public class RestTemplateUtils { private static final RestTemplate restTemplate = new RestTemplate(); // ----------------------------------GET------------------------------------------------------- /** * GET請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType) { return restTemplate.getForEntity(url, responseType); } /** * GET請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Object... uriVariables) { return restTemplate.getForEntity(url, responseType, uriVariables); } /** * GET請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.getForEntity(url, responseType, uriVariables); } /** * 帶請求頭的GET請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return get(url, httpHeaders, responseType, uriVariables); } /** * 帶請求頭的GET請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) { HttpEntity<?> requestEntity = new HttpEntity<>(headers); return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables); } /** * 帶請求頭的GET請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return get(url, httpHeaders, responseType, uriVariables); } /** * 帶請求頭的GET請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> get(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<?> requestEntity = new HttpEntity<>(headers); return exchange(url, HttpMethod.GET, requestEntity, responseType, uriVariables); } // ----------------------------------POST------------------------------------------------------- /** * POST請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @return */ public static <T> ResponseEntity<T> post(String url, Class<T> responseType) { return restTemplate.postForEntity(url, HttpEntity.EMPTY, responseType); } /** * POST請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) { return restTemplate.postForEntity(url, requestBody, responseType); } /** * POST請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Object... uriVariables) { return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); } /** * POST請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.postForEntity(url, requestBody, responseType, uriVariables); } /** * 帶請求頭的POST請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return post(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的POST請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return post(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的POST請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return post(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的POST請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return post(url, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的POST請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的POST請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType, uriVariables); } // ----------------------------------PUT------------------------------------------------------- /** * PUT請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, Class<T> responseType, Object... uriVariables) { return put(url, HttpEntity.EMPTY, responseType, uriVariables); } /** * PUT請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody); return put(url, requestEntity, responseType, uriVariables); } /** * PUT請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody); return put(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的PUT請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return put(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的PUT請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return put(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的PUT請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return put(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的PUT請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return put(url, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的PUT請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的PUT請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> put(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables); } // ----------------------------------DELETE------------------------------------------------------- /** * DELETE請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Object... uriVariables) { return delete(url, HttpEntity.EMPTY, responseType, uriVariables); } /** * DELETE請求調用方式 * * @param url 請求URL * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Class<T> responseType, Map<String, ?> uriVariables) { return delete(url, HttpEntity.EMPTY, responseType, uriVariables); } /** * DELETE請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody); return delete(url, requestEntity, responseType, uriVariables); } /** * DELETE請求調用方式 * * @param url 請求URL * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody); return delete(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return delete(url, httpHeaders, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers); return delete(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return delete(url, httpHeaders, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers); return delete(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return delete(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return delete(url, requestEntity, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, Map<String, String> headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAll(headers); return delete(url, httpHeaders, requestBody, responseType, uriVariables); } /** * 帶請求頭的DELETE請求調用方式 * * @param url 請求URL * @param headers 請求頭參數 * @param requestBody 請求參數體 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) { HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers); return delete(url, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的DELETE請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables); } /** * 自定義請求頭和請求體的DELETE請求調用方式 * * @param url 請求URL * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> delete(String url, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables); } // ----------------------------------通用方法------------------------------------------------------- /** * 通用調用方式 * * @param url 請求URL * @param method 請求方法類型 * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,按順序依次對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) { return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables); } /** * 通用調用方式 * * @param url 請求URL * @param method 請求方法類型 * @param requestEntity 請求頭和請求體封裝對象 * @param responseType 返回對象類型 * @param uriVariables URL中的變量,與Map中的key對應 * @return ResponseEntity 響應對象封裝類 */ public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) { return restTemplate.exchange(url, method, requestEntity, responseType, uriVariables); } /** * 獲取RestTemplate實例對象,可自由調用其方法 * * @return RestTemplate實例對象 */ public static RestTemplate getRestTemplate() { return restTemplate; } }
//發送Get請求, 須要將請求Url用佔位符 //如下兩種方式任可 String urlGet = "http://127.0.0.1:8888/demo/get"; String urlGet2 = "http://127.0.0.1:8888/demo/get?name={name}&age={age}"; UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(urlGet); Map<String, Object> param = new HashMap<>(); param.put("name","yamo"); param.put("age",11); param.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(),o.getValue())); String url3 = builder.build().encode().toString(); System.out.println(url3); ResponseEntity<String> entity = RestTemplateUtils.get(url3,String.class,param); // ResponseEntity<String> entity2 = RestTemplateUtils.get(url2,String.class,param); System.out.println(entity.getStatusCodeValue()); //200 System.out.println(entity.getStatusCode()); //200 OK System.out.println(entity.getBody()); //接口返回的結果
String url = "http://127.0.0.1:8888/demo/post"; HashMap<String, String> header = new HashMap<>(); //測試普通表單參數的POST請求 MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); requestBody.add("name", "Logan"); requestBody.add("age", 12); ResponseEntity<String> response = RestTemplateUtils.post(url, header,requestBody, String.class); System.out.println(response.getStatusCode().value()); //200 System.out.println(response.getBody()); //接口返回 //測試JSON格式請求體Body方式POST請求 header.put("Content-Type", "application/json; charset=utf-8"); JSONObject requestBody = new JSONObject(); requestBody.put("name", "Logan"); requestBody.put("age", 16); ResponseEntity<String> response = RestTemplateUtils.post(url, header,requestBody, String.class); System.out.println(response.getStatusCode().value()); //200 System.out.println(response.getBody()); //接口返回
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.2</version> </dependency>
import com.alibaba.fastjson.JSON; import okhttp3.*; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.URLEncoder; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @description: * @author: yangshuai * @create: 2020-05-21 18:03 **/ public class OkHttpUtils { private static volatile OkHttpClient okHttpClient = null; private static volatile Semaphore semaphore = null; private Map<String, String> headerMap; private Map<String, String> paramMap; private Map<String, Object> jsonParamMap; private String url; private Request.Builder request; /** * 初始化okHttpClient,而且容許https訪問 */ private OkHttpUtils() { if (okHttpClient == null) { synchronized (OkHttpUtils.class) { if (okHttpClient == null) { TrustManager[] trustManagers = buildTrustManagers(); okHttpClient = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0]) .hostnameVerifier((hostName, session) -> true) .retryOnConnectionFailure(true) .build(); addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"); } } } } /** * 用於異步請求時,控制訪問線程數,返回結果 * * @return */ private static Semaphore getSemaphoreInstance() { //只能1個線程同時訪問 synchronized (OkHttpUtils.class) { if (semaphore == null) { semaphore = new Semaphore(0); } } return semaphore; } /** * 建立OkHttpUtils * * @return */ public static OkHttpUtils builder() { return new OkHttpUtils(); } /** * 添加url * * @param url * @return */ public OkHttpUtils url(String url) { this.url = url; return this; } /** * 添加參數 * * @param key 參數名 * @param value 參數值 * @return */ public OkHttpUtils addParam(String key, String value) { if (paramMap == null) { paramMap = new LinkedHashMap<>(16); } paramMap.put(key, value); return this; } /** * 爲了傳json時的int類型 * @param key * @param value * @return */ public OkHttpUtils addJsonParam(String key, Object value) { if (jsonParamMap== null) { jsonParamMap = new LinkedHashMap<>(16); } jsonParamMap.put(key, value); return this; } /** * 添加請求頭 * * @param key 參數名 * @param value 參數值 * @return */ public OkHttpUtils addHeader(String key, String value) { if (headerMap == null) { headerMap = new LinkedHashMap<>(16); } headerMap.put(key, value); return this; } /** * 初始化get方法 * * @return */ public OkHttpUtils get() { request = new Request.Builder().get(); StringBuilder urlBuilder = new StringBuilder(url); if (paramMap != null) { urlBuilder.append("?"); try { for (Map.Entry<String, String> entry : paramMap.entrySet()) { urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")). append("="). append(URLEncoder.encode(entry.getValue(), "utf-8")). append("&"); } } catch (Exception e) { e.printStackTrace(); } urlBuilder.deleteCharAt(urlBuilder.length() - 1); } request.url(urlBuilder.toString()); return this; } /** * 初始化post方法 * * @param isJsonPost true等於json的方式提交數據,相似postman裏post方法的raw * false等於普通的表單提交 * @return */ public OkHttpUtils post(boolean isJsonPost) { RequestBody requestBody; if (isJsonPost) { String json = ""; if (jsonParamMap != null) { json = JSON.toJSONString(jsonParamMap); } requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); } else { FormBody.Builder formBody = new FormBody.Builder(); if (paramMap != null) { paramMap.forEach(formBody::add); } requestBody = formBody.build(); } request = new Request.Builder().post(requestBody).url(url); return this; } /** * 同步請求 * * @return */ public String sync() { setHeader(request); try { Response response = okHttpClient.newCall(request.build()).execute(); assert response.body() != null; return response.body().string(); } catch (IOException e) { e.printStackTrace(); return "請求失敗:" + e.getMessage(); } } /** * 異步請求,有返回值 */ public String async() { StringBuilder buffer = new StringBuilder(""); setHeader(request); okHttpClient.newCall(request.build()).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { buffer.append("請求出錯:").append(e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { assert response.body() != null; buffer.append(response.body().string()); getSemaphoreInstance().release(); } }); try { getSemaphoreInstance().acquire(); } catch (InterruptedException e) { e.printStackTrace(); } return buffer.toString(); } /** * 異步請求,帶有接口回調 * * @param callBack */ public void async(ICallBack callBack) { setHeader(request); okHttpClient.newCall(request.build()).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callBack.onFailure(call, e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { assert response.body() != null; callBack.onSuccessful(call, response.body().string()); } }); } /** * 爲request添加請求頭 * * @param request */ private void setHeader(Request.Builder request) { if (headerMap != null) { try { for (Map.Entry<String, String> entry : headerMap.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } catch (Exception e) { e.printStackTrace(); } } } /** * 生成安全套接字工廠,用於https請求的證書跳過 * * @return */ private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) { SSLSocketFactory ssfFactory = null; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); ssfFactory = sc.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return ssfFactory; } private static TrustManager[] buildTrustManagers() { return new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } }; } /** * 自定義一個接口回調 */ public interface ICallBack { void onSuccessful(Call call, String data); void onFailure(Call call, String errorMsg); } }
String urlGet = "http://127.0.0.1:8888/demo/get"; String sync = OkHttpUtils .builder() .url(urlGet) // 有參數的話添加參數,可多個 addParam 只能加入string類型的value .addParam("name", "yamo") .addParam("age", "11") // 也能夠添加多個 .addHeader("Content-Type", "application/json; charset=utf-8") .get() // 可選擇是同步請求仍是異步請求 //.async(); .sync(); System.out.println(sync); //返回的response.body().string();
String urlPost = "http://127.0.0.1:8888/demo/post"; String sync = OkHttpUtils .builder() .url(urlPost) //.addHeader() .addJsonParam("name", "yamo") .addJsonParam("age", 11) // 若是是true的話,會相似於postman中post提交方式的raw,用json的方式提交,不是表單 // 若是是false的話傳統的表單提交 .post(true) .sync(); System.out.println(sync); //返回的response.body().string();
import com.alibaba.fastjson.JSON; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; 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.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.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.*; import java.net.URI; import java.nio.charset.Charset; import java.util.*; public class HttpClientUtil { protected final Log LOG = LogFactory.getLog(HttpClientUtil.class); private static HttpClientUtil instance; protected Charset charset; private HttpClientUtil(){} public static HttpClientUtil getInstance() { return getInstance(Charset.defaultCharset()); } public static HttpClientUtil getInstance(Charset charset){ if(instance == null){ instance = new HttpClientUtil(); } instance.setCharset(charset); return instance; } public void setCharset(Charset charset) { this.charset = charset; } /** * post請求 */ public String doPost(String url) throws Exception { return doPost(url, null, null); } public String doPost(String url, Map<String, Object> params) throws Exception { return doPost(url, params, null); } public String doPost(String url, Map<String, Object> params, Map<String, String> header) throws Exception { String body = null; try { // Post請求 LOG.debug(" protocol: POST"); LOG.debug(" url: " + url); HttpPost httpPost = new HttpPost(url.trim()); // 設置參數 LOG.debug(" params: " + JSON.toJSONString(params)); httpPost.setEntity(new UrlEncodedFormEntity(map2NameValuePairList(params), charset)); // 設置Header if (header != null && !header.isEmpty()) { LOG.debug(" header: " + JSON.toJSONString(header)); for (Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } // 發送請求,獲取返回數據 body = execute(httpPost); } catch (Exception e) { throw e; } LOG.debug(" result: " + body); return body; } /** * postJson請求 */ public String doPostJson(String url, Map<String, Object> params) throws Exception { return doPostJson(url, params, null); } public String doPostJson(String url, Map<String, Object> params, Map<String, String> header) throws Exception { String json = null; if (params != null && !params.isEmpty()) { for (Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next(); Object object = entry.getValue(); if (object == null) { it.remove(); } } json = JSON.toJSONString(params); } return postJson(url, json, header); } public String doPostJson(String url, String json) throws Exception { return doPostJson(url, json, null); } public String doPostJson(String url, String json, Map<String, String> header) throws Exception { return postJson(url, json, header); } private String postJson(String url, String json, Map<String, String> header) throws Exception { String body = null; try { // Post請求 LOG.debug(" protocol: POST"); LOG.debug(" url: " + url); HttpPost httpPost = new HttpPost(url.trim()); // 設置參數 LOG.debug(" params: " + json); httpPost.setEntity(new StringEntity(json, ContentType.DEFAULT_TEXT.withCharset(charset))); httpPost.setHeader(new BasicHeader("Content-Type", "application/json")); LOG.debug(" type: JSON"); // 設置Header if (header != null && !header.isEmpty()) { LOG.debug(" header: " + JSON.toJSONString(header)); for (Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); httpPost.setHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } // 發送請求,獲取返回數據 body = execute(httpPost); } catch (Exception e) { throw e; } LOG.debug(" result: " + body); return body; } /** * get請求 */ public String doGet(String url) throws Exception { return doGet(url, null, null); } public String doGet(String url, Map<String, String> header) throws Exception { return doGet(url, null, header); } public String doGet(String url, Map<String, Object> params, Map<String, String> header) throws Exception { String body = null; try { // Get請求 LOG.debug("protocol: GET"); HttpGet httpGet = new HttpGet(url.trim()); // 設置參數 if (params != null && !params.isEmpty()) { String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params), charset)); String uri = httpGet.getURI().toString(); if(uri.indexOf("?") >= 0){ httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str)); }else { httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str)); } } LOG.debug(" url: " + httpGet.getURI()); // 設置Header if (header != null && !header.isEmpty()) { LOG.debug(" header: " + header); for (Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); httpGet.setHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } // 發送請求,獲取返回數據 body = execute(httpGet); } catch (Exception e) { throw e; } LOG.debug(" result: " + body); return body; } /** * 下載文件 */ public void doDownload(String url, String path) throws Exception { download(url, null, path); } public void doDownload(String url, Map<String, Object> params, String path) throws Exception { download(url, params, path); } /** * 上傳文件 */ public String doUpload(String url, String name, String path) throws Exception { Map<String, Object> params = new HashMap<String, Object>(); params.put(name, new File(path)); return doUpload(url, params); } public String doUpload(String url, Map<String, Object> params) throws Exception { String body = null; // Post請求 HttpPost httpPost = new HttpPost(url.trim()); // 設置參數 MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.setCharset(charset); if (params != null && !params.isEmpty()) { Iterator<String> it = params.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object value = params.get(key); if (value instanceof File) { FileBody fileBody = new FileBody((File) value); entityBuilder.addPart(key, fileBody); } else { entityBuilder.addPart(key, new StringBody(String.valueOf(value), ContentType.DEFAULT_TEXT.withCharset(charset))); } } } HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); // 發送請求,獲取返回數據 body = execute(httpPost); return body; } private void download(String url, Map<String, Object> params, String path) throws Exception { // Get請求 HttpGet httpGet = new HttpGet(url.trim()); if (params != null && !params.isEmpty()) { // 設置參數 String str = EntityUtils.toString(new UrlEncodedFormEntity(map2NameValuePairList(params))); String uri = httpGet.getURI().toString(); if (uri.indexOf("?") >= 0) { httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str)); } else { httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str)); } } // 發送請求,下載文件 downloadFile(httpGet, path); } private void downloadFile(HttpRequestBase requestBase, String path) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { CloseableHttpResponse response = httpclient.execute(requestBase); try { HttpEntity entity = response.getEntity(); if (entity != null) { byte[] b = EntityUtils.toByteArray(entity); OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path))); out.write(b); out.flush(); out.close(); } EntityUtils.consume(entity); } catch (Exception e) { throw e; } finally { response.close(); } } catch (Exception e) { throw e; } finally { httpclient.close(); } } private String execute(HttpRequestBase requestBase) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String body = null; try { CloseableHttpResponse response = httpclient.execute(requestBase); try { HttpEntity entity = response.getEntity(); if (entity != null) { body = EntityUtils.toString(entity, charset.toString()); } EntityUtils.consume(entity); } catch (Exception e) { throw e; }finally { response.close(); } } catch (Exception e) { throw e; } finally { httpclient.close(); } return body; } private List<NameValuePair> map2NameValuePairList(Map<String, Object> params) { if (params != null && !params.isEmpty()) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator<String> it = params.keySet().iterator(); while (it.hasNext()) { String key = it.next(); if(params.get(key) != null) { String value = String.valueOf(params.get(key)); list.add(new BasicNameValuePair(key, value)); } } return list; } return null; } //發送restful的get post put 和 delete 請求 public String doPut(String url, String entityString, Map<String,String> headerMap) throws Exception { String body = null; HttpPut httpput = new HttpPut(url); try{ httpput.setEntity(new StringEntity(entityString)); for(Map.Entry<String, String> entry : headerMap.entrySet()) { httpput.addHeader(entry.getKey(), entry.getValue()); } //發送put請求 body = execute(httpput); }catch (Exception e) { e.printStackTrace(); throw e; } return body; } public String doDelete(String url, Map<String, String> header) throws Exception{ String body = null; HttpDelete httpdel = new HttpDelete(url); try{ // 設置Header if (header != null && !header.isEmpty()) { LOG.debug(" header: " + header); for (Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); httpdel.setHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } body = execute(httpdel); }catch (Exception e) { e.printStackTrace(); throw e; } return body; } }