生活随笔
收集整理的這篇文章主要介紹了
HttpClient4.5 简单入门实例(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、所需要的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
; } public String
sendHttpPost(String httpUrl
) { HttpPost httpPost
= new
HttpPost(httpUrl
);return sendHttpPost(httpPost
); } public String
sendHttpPost(String httpUrl
, String params
) { HttpPost httpPost
= new
HttpPost(httpUrl
);try
{ 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
); } public String
sendHttpPost(String httpUrl
, Map
<String
, String
> maps
) { HttpPost httpPost
= new
HttpPost(httpUrl
);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
); } public String
sendHttpPost(String httpUrl
, Map
<String
, String
> maps
, List
<File
> fileLists
) { HttpPost httpPost
= new
HttpPost(httpUrl
);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
); } private String
sendHttpPost(HttpPost httpPost
) { CloseableHttpClient httpClient
= null
; CloseableHttpResponse response
= null
; HttpEntity entity
= null
; String responseContent
= null
; try
{ httpClient
= HttpClients
.createDefault(); httpPost
.setConfig(requestConfig
); response
= httpClient
.execute(httpPost
); entity
= response
.getEntity(); responseContent
= EntityUtils
.toString(entity
, "UTF-8"); } catch
(Exception e
) { e
.printStackTrace(); } finally
{ try
{ if (response
!= null
) { response
.close(); } if (httpClient
!= null
) { httpClient
.close(); } } catch
(IOException e
) { e
.printStackTrace(); } } return responseContent
; } public String
sendHttpGet(String httpUrl
) { HttpGet httpGet
= new
HttpGet(httpUrl
);return sendHttpGet(httpGet
); } public String
sendHttpsGet(String httpUrl
) { HttpGet httpGet
= new
HttpGet(httpUrl
);return sendHttpsGet(httpGet
); } private String
sendHttpGet(HttpGet httpGet
) { CloseableHttpClient httpClient
= null
; CloseableHttpResponse response
= null
; HttpEntity entity
= null
; String responseContent
= null
; try
{ httpClient
= HttpClients
.createDefault(); httpGet
.setConfig(requestConfig
); response
= httpClient
.execute(httpGet
); entity
= response
.getEntity(); responseContent
= EntityUtils
.toString(entity
, "UTF-8"); } catch
(Exception e
) { e
.printStackTrace(); } finally
{ try
{ if (response
!= null
) { response
.close(); } if (httpClient
!= null
) { httpClient
.close(); } } catch
(IOException e
) { e
.printStackTrace(); } } return responseContent
; } private String
sendHttpsGet(HttpGet httpGet
) { CloseableHttpClient httpClient
= null
; CloseableHttpResponse response
= null
; HttpEntity entity
= null
; String responseContent
= null
; try
{ PublicSuffixMatcher publicSuffixMatcher
= PublicSuffixMatcherLoader
.load(new
URL(httpGet
.getURI().toString())); DefaultHostnameVerifier hostnameVerifier
= new
DefaultHostnameVerifier(publicSuffixMatcher
); httpClient
= HttpClients
.custom().setSSLHostnameVerifier(hostnameVerifier
).build(); httpGet
.setConfig(requestConfig
); response
= httpClient
.execute(httpGet
); entity
= response
.getEntity(); responseContent
= EntityUtils
.toString(entity
, "UTF-8"); } catch
(Exception e
) { e
.printStackTrace(); } finally
{ try
{ 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
); } }
服務端代碼:
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
; }
}
總結
以上是生活随笔為你收集整理的HttpClient4.5 简单入门实例(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。