您好,登錄后才能下訂單哦!
這篇文章主要介紹HttpClient、okhttp和RestTemplate的區別是什么,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
<!--HttpClient--> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
public class HttpClientUtil { /** * httpClient的get請求方式 * 使用GetMethod來訪問一個URL對應的網頁實現步驟: * 1.生成一個HttpClient對象并設置相應的參數; * 2.生成一個GetMethod對象并設置響應的參數; * 3.用HttpClient生成的對象來執行GetMethod生成的Get方法; * 4.處理響應狀態碼; * 5.若響應正常,處理HTTP響應內容; * 6.釋放連接。 * @param url * @param charset * @return */ public static String doGet(String url, String charset) { //1.生成HttpClient對象并設置參數 HttpClient httpClient = new HttpClient(); //設置Http連接超時為5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //2.生成GetMethod對象并設置參數 GetMethod getMethod = new GetMethod(url); //設置get請求超時為5秒 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); //設置請求重試處理,用的是默認的重試處理:請求三次 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); String response = ""; //3.執行HTTP GET 請求 try { int statusCode = httpClient.executeMethod(getMethod); //4.判斷訪問的狀態碼 if (statusCode != HttpStatus.SC_OK) { System.err.println("請求出錯:" + getMethod.getStatusLine()); } //5.處理HTTP響應內容 //HTTP響應頭部信息,這里簡單打印 Header[] headers = getMethod.getResponseHeaders(); for(Header h : headers) { System.out.println(h.getName() + "---------------" + h.getValue()); } //讀取HTTP響應內容,這里簡單打印網頁內容 //讀取為字節數組 byte[] responseBody = getMethod.getResponseBody(); response = new String(responseBody, charset); System.out.println("-----------response:" + response); //讀取為InputStream,在網頁內容數據量大時候推薦使用 //InputStream response = getMethod.getResponseBodyAsStream(); } catch (HttpException e) { //發生致命的異常,可能是協議不對或者返回的內容有問題 System.out.println("請檢查輸入的URL!"); e.printStackTrace(); } catch (IOException e) { //發生網絡異常 System.out.println("發生網絡異常!"); } finally { //6.釋放連接 getMethod.releaseConnection(); } return response; } /** * post請求 * @param url * @param json * @return */ public static String doPost(String url, JSONObject json){ HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("accept", "*/*"); postMethod.addRequestHeader("connection", "Keep-Alive"); //設置json格式傳送 postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK"); //必須設置下面這個Header postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); //添加請求參數 postMethod.addParameter("commentId", json.getString("commentId")); String res = ""; try { int code = httpClient.executeMethod(postMethod); if (code == 200){ res = postMethod.getResponseBodyAsString(); System.out.println(res); } } catch (IOException e) { e.printStackTrace(); } return res; } public static void main(String[] args) { System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK")); System.out.println("-----------分割線------------"); System.out.println("-----------分割線------------"); System.out.println("-----------分割線------------"); JSONObject jsonObject = new JSONObject(); jsonObject.put("commentId", "13026194071"); System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject)); } }
代碼復雜,還得操心資源回收等。代碼很復雜,冗余代碼多,不建議直接使用。
OkHttp是一個高效的HTTP客戶端,允許所有同一個主機地址的請求共享同一個socket連接;連接池減少請求延時;透明的GZIP壓縮減少響應數據的大小;緩存響應內容,避免一些完全重復的請求
當網絡出現問題的時候OkHttp依然堅守自己的職責,它會自動恢復一般的連接問題,如果你的服務有多個IP地址,當第一個IP請求失敗時,OkHttp會交替嘗試你配置的其他IP,OkHttp使用現代TLS技術(SNI, ALPN)初始化新的連接,當握手失敗時會回退到TLS 1.0。
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.10.0</version> </dependency>
它的請求/響應 API 使用構造器模式builders來設計,它支持阻塞式的同步請求和帶回調的異步請求。
@Configuration public class OkHttpConfig { @Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() //.sslSocketFactory(sslSocketFactory(), x509TrustManager()) .retryOnConnectionFailure(false) .connectionPool(pool()) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30,TimeUnit.SECONDS) .build(); } @Bean public X509TrustManager x509TrustManager() { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; } @Bean public SSLSocketFactory sslSocketFactory() { try { //信任任何鏈接 SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom()); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; } /** * Create a new connection pool with tuning parameters appropriate for a single-user application. * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently */ @Bean public ConnectionPool pool() { return new ConnectionPool(200, 5, TimeUnit.MINUTES); } }
@Slf4j public class OkHttpClient { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private volatile static okhttp3.OkHttpClient client; private static final int MAX_IDLE_CONNECTION = Integer .parseInt(ConfigManager.get("httpclient.max_idle_connection")); private static final long KEEP_ALIVE_DURATION = Long .parseLong(ConfigManager.get("httpclient.keep_alive_duration")); private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout")); private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. ")); /** * 單例模式(雙重檢查模式) 獲取類實例 * * @return client */ private static okhttp3.OkHttpClient getInstance() { if (client == null) { synchronized (okhttp3.OkHttpClient.class) { if (client == null) { client = new okhttp3.OkHttpClient.Builder() .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION, TimeUnit.MINUTES)) .build(); } } } return client; } public static String syncPost(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); try { Response response = OkHttpClient.getInstance().newCall(request).execute(); if (response.isSuccessful()) { String result = response.body().string(); log.info("syncPost response = {}, responseBody= {}", response, result); return result; } String result = response.body().string(); log.info("syncPost response = {}, responseBody= {}", response, result); throw new IOException("三方接口返回http狀態碼為" + response.code()); } catch (Exception e) { log.error("syncPost() url:{} have a ecxeption {}", url, e); throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage()); } } public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException { Request request; final Request.Builder builder = new Request.Builder().url(url); try { if (!CollectionUtils.isEmpty(headParamsMap)) { final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet() .iterator(); while (iterator.hasNext()) { final Map.Entry<String, Object> entry = iterator.next(); builder.addHeader(entry.getKey(), (String) entry.getValue()); } } request = builder.build(); Response response = OkHttpClient.getInstance().newCall(request).execute(); String result = response.body().string(); log.info("syncGet response = {},responseBody= {}", response, result); if (!response.isSuccessful()) { throw new IOException("三方接口返回http狀態碼為" + response.code()); } return result; } catch (Exception e) { log.error("remote interface url:{} have a ecxeption {}", url, e); throw new RuntimeException("三方接口返回異常"); } } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
// 1-getForObject() User user1 = this.restTemplate.getForObject(uri, User.class); // 2-getForEntity() ResponseEntity<User> responseEntity1 = this.restTemplate.getForEntity(uri, User.class); HttpStatus statusCode = responseEntity1.getStatusCode(); HttpHeaders header = responseEntity1.getHeaders(); User user2 = responseEntity1.getBody(); // 3-exchange() RequestEntity requestEntity = RequestEntity.get(new URI(uri)).build(); ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class); User user3 = responseEntity2.getBody();
方式一:
Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}" , Notice.class,1,5);
方式二:
Map<String,String> map = new HashMap(); map.put("start","1"); map.put("page","5"); Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/" , Notice.class,map);
// 1-postForObject() User user1 = this.restTemplate.postForObject(uri, user, User.class); // 2-postForEntity() ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class); // 3-exchange() RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user); ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
方式一:
String url = "http://demo/api/book/"; HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); String requestJson = "{...}"; HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers); String result = restTemplate.postForObject(url, entity, String.class); System.out.println(result);
方式二:
@Test public void rtPostObject(){ RestTemplate restTemplate = new RestTemplate(); String url = "http://47.xxx.xxx.96/register/checkEmail"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("email", "844072586@qq.com"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class ); System.out.println(response.getBody()); }
使用RestTemplate發送請求,當請求體是String時,應這樣配置:
RestTemplate restTemplate = new RestTemplate(factory); restTemplate .getMessageConverters() .set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
如果沒有自定義StringHttpMessageConverter,默認的StringHttpMessageConverter使用的字符集是ISO_8859_1,當請求體包含中文時,會亂碼。
以上是“HttpClient、okhttp和RestTemplate的區別是什么”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。