日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HttpClient4.5 简单入门实例(一)

發(fā)布時間:2024/9/27 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HttpClient4.5 简单入门实例(一) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、所需要的jar包

httpclient-4.5.jar

httpcore-4.4.1.jar

httpmime-4.5.jar
二、實例

package com.gblfy.test;import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; 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.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; 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.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { private RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(15000) .setConnectTimeout(15000) .setConnectionRequestTimeout(15000) .build(); private static HttpClientUtil instance = null; private HttpClientUtil(){} public static HttpClientUtil getInstance(){ if (instance == null) { instance = new HttpClientUtil(); } return instance; } /** * 發(fā)送 post請求 * @param httpUrl 地址 */ public String sendHttpPost(String httpUrl) { HttpPost httpPost = new HttpPost(httpUrl);// 創(chuàng)建httpPost return sendHttpPost(httpPost); } /** * 發(fā)送 post請求 * @param httpUrl 地址 * @param params 參數(shù)(格式:key1=value1&key2=value2) */ public String sendHttpPost(String httpUrl, String params) { HttpPost httpPost = new HttpPost(httpUrl);// 創(chuàng)建httpPost try { //設(shè)置參數(shù) StringEntity stringEntity = new StringEntity(params, "UTF-8"); stringEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(stringEntity); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 發(fā)送 post請求 * @param httpUrl 地址 * @param maps 參數(shù) */ public String sendHttpPost(String httpUrl, Map<String, String> maps) { HttpPost httpPost = new HttpPost(httpUrl);// 創(chuàng)建httpPost // 創(chuàng)建參數(shù)隊列 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } return sendHttpPost(httpPost); } /** * 發(fā)送 post請求(帶文件) * @param httpUrl 地址 * @param maps 參數(shù) * @param fileLists 附件 */ public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) { HttpPost httpPost = new HttpPost(httpUrl);// 創(chuàng)建httpPost MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); for (String key : maps.keySet()) { meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); } for(File file : fileLists) { FileBody fileBody = new FileBody(file); meBuilder.addPart("files", fileBody); } HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpPost(httpPost); } /** * 發(fā)送Post請求 * @param httpPost * @return */ private String sendHttpPost(HttpPost httpPost) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 創(chuàng)建默認(rèn)的httpClient實例. httpClient = HttpClients.createDefault(); httpPost.setConfig(requestConfig); // 執(zhí)行請求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { // 關(guān)閉連接,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseContent; } /** * 發(fā)送 get請求 * @param httpUrl */ public String sendHttpGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl);// 創(chuàng)建get請求 return sendHttpGet(httpGet); } /** * 發(fā)送 get請求Https * @param httpUrl */ public String sendHttpsGet(String httpUrl) { HttpGet httpGet = new HttpGet(httpUrl);// 創(chuàng)建get請求 return sendHttpsGet(httpGet); } /** * 發(fā)送Get請求 * @param httpPost * @return */ private String sendHttpGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 創(chuàng)建默認(rèn)的httpClient實例. httpClient = HttpClients.createDefault(); httpGet.setConfig(requestConfig); // 執(zhí)行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { // 關(guān)閉連接,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseContent; } /** * 發(fā)送Get請求Https * @param httpPost * @return */ private String sendHttpsGet(HttpGet httpGet) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try { // 創(chuàng)建默認(rèn)的httpClient實例. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString())); DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build(); httpGet.setConfig(requestConfig); // 執(zhí)行請求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { // 關(guān)閉連接,釋放資源 if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return responseContent; } }

客戶端代碼:

package com.gblfy.test;import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class HttpClientUtilTest { @Test public void testSendHttpPost1() { String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://localhost:8081/gblfy/test/send?username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost2() { String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://localhost:8081/gblfy/test/send", "username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost3() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://localhost:8081/gblfy/test/send", maps); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpPost4() { Map<String, String> maps = new HashMap<String, String>(); maps.put("username", "test01"); maps.put("password", "123456"); List<File> fileLists = new ArrayList<File>(); fileLists.add(new File("D://test//httpclient//1.png")); fileLists.add(new File("D://test//httpclient//1.txt")); String responseContent = HttpClientUtil.getInstance() .sendHttpPost("http://localhost:8081/gblfy/test/sendpost/file", maps, fileLists); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpGet() { String responseContent = HttpClientUtil.getInstance() .sendHttpGet("http://localhost:8081/gblfy/test/send?username=test01&password=123456"); System.out.println("reponse content:" + responseContent); } @Test public void testSendHttpsGet() { String responseContent = HttpClientUtil.getInstance() .sendHttpsGet("https://www.baidu.com"); System.out.println("reponse content:" + responseContent); } }

服務(wù)端代碼:

package com.gblfy.web;import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.stereotype.Controller;@Controller public class Controller {@RequestMapping(value = "/test/send") @ResponseBody public Map<String, String> sendPost(HttpServletRequest request) { Map<String, String> maps = new HashMap<String, String>(); String username = request.getParameter("username"); String password = request.getParameter("password"); maps.put("username", username); maps.put("password", password); return maps; } @RequestMapping(value = "/test/sendpost/file",method=RequestMethod.POST) @ResponseBody public Map<String, String> sendPostFile(@RequestParam("files") MultipartFile [] files,HttpServletRequest request) { Map<String, String> maps = new HashMap<String, String>(); String username = request.getParameter("username"); String password = request.getParameter("password"); maps.put("username", username); maps.put("password", password); try { for(MultipartFile file : files){ String fileName = file.getOriginalFilename(); fileName = new String(fileName.getBytes(),"UTF-8"); InputStream is = file.getInputStream(); if (fileName != null && !("".equals(fileName))) { File directory = new File("D://test//httpclient//file"); if (!directory.exists()) { directory.mkdirs(); } String filePath = ("D://test//httpclient//file") + File.separator + fileName; FileOutputStream fos = new FileOutputStream(filePath); byte[] buffer = new byte[1024]; while (is.read(buffer) > 0) { fos.write(buffer, 0, buffer.length); } fos.flush(); fos.close(); maps.put("file--"+fileName, "uploadSuccess"); } } } catch (Exception e) { e.printStackTrace(); } return maps; } }

總結(jié)

以上是生活随笔為你收集整理的HttpClient4.5 简单入门实例(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。