參看httpclient項(xiàng)目代碼
代碼實(shí)現(xiàn)
/**
* GET請求
* @param httpUrl
* @return
*/
public static String doGet(String httpUrl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;//返回結(jié)果字符串
try {
//創(chuàng)建遠(yuǎn)程url連接對象
URL url = new URL(httpUrl);
//通過遠(yuǎn)程url連接對象打開一個(gè)連接,強(qiáng)轉(zhuǎn)成httpURLConnection類
connection = (HttpURLConnection) url.openConnection();
//設(shè)置連接方式:get
connection.setRequestMethod("GET");
//設(shè)置連接主機(jī)服務(wù)器的超時(shí)時(shí)間:15000毫秒
connection.setConnectTimeout(15000);
//設(shè)置讀取遠(yuǎn)程返回的數(shù)據(jù)時(shí)間:60000毫秒
connection.setReadTimeout(60000);
//通過connection連接,獲取輸入流
is = connection.getInputStream();
//封裝輸入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
//存放數(shù)據(jù)
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");//回車+換行
}
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
//關(guān)閉資源
if(null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();//關(guān)閉遠(yuǎn)程連接
}
return result;
}
/**
* POST 請求
* @param httpUrl
* @param param
* @return
*/
public static String doPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
//創(chuàng)建遠(yuǎn)程url連接對象
URL url = new URL(httpUrl);
//通過遠(yuǎn)程url連接對象打開連接
connection = (HttpURLConnection) url.openConnection();
//設(shè)置連接請求方式
connection.setRequestMethod("POST");
//設(shè)置連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
connection.setConnectTimeout(15000);
//設(shè)置讀取主機(jī)服務(wù)器返回?cái)?shù)據(jù)超時(shí)時(shí)間:60000毫秒
connection.setReadTimeout(60000);
//默認(rèn)值為:false,當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫數(shù)據(jù)時(shí),需要設(shè)置為true
connection.setDoOutput(true);
//默認(rèn)值為:true,當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時(shí),設(shè)置為true,該參數(shù)可有可無
connection.setDoInput(true);
//通過連接對象獲取一個(gè)輸出流
os = connection.getOutputStream();
//通過輸出流對象將參數(shù)寫出去/傳輸出去,它是通過字節(jié)數(shù)組寫出的
os.write(param.getBytes());//把需要傳送的參數(shù)發(fā)送給遠(yuǎn)程url
//通過連接對象獲取一個(gè)輸入流,向遠(yuǎn)程讀取
is = connection.getInputStream();
//對輸入流對象進(jìn)行包裝
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
//循環(huán)遍歷一行一行讀取數(shù)據(jù)
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
//關(guān)閉資源
if(null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//斷開與遠(yuǎn)程地址url的連接
connection.disconnect();
}
return result;
}
HttpClient 3.1
⒈ 添加依賴
<!-- httpclient3.1版本 -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
⒉ 代碼實(shí)現(xiàn)
/**
* GET 請求方法
* 注:如果需要傳遞參數(shù),把參數(shù)拼接在url地址后面
* @param url
*/
public static String doGet(String url) {
//輸入流
InputStream is = null;
BufferedReader br = null;
String result = null;
//創(chuàng)建httpClient實(shí)例
HttpClient httpClient = new HttpClient();
//設(shè)置http連接主機(jī)服務(wù)超時(shí)時(shí)間:15000毫秒
//先獲取連接管理器對象,再獲取參數(shù)對象,再進(jìn)行參數(shù)的賦值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
//創(chuàng)建一個(gè)Get方法實(shí)例對象
GetMethod getMethod = new GetMethod(url);
//設(shè)置get請求超時(shí)為60000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
//設(shè)置請求重試機(jī)制,默認(rèn)重試次數(shù):3次,參數(shù)設(shè)置為true,重試機(jī)制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));
try {
//執(zhí)行Get方法
int statusCode = httpClient.executeMethod(getMethod);
//判斷返回碼
if(statusCode != HttpStatus.SC_OK) {
//如果狀態(tài)碼返回的不是ok,說明失敗了,打印錯(cuò)誤信息
System.err.println("Method faild: " + getMethod.getStatusLine());
}
//通過getMethod實(shí)例,獲取遠(yuǎn)程的一個(gè)輸入流
is = getMethod.getResponseBodyAsStream();
//包裝輸入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
//讀取封裝的輸入流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
} catch (Exception e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} finally {
//關(guān)閉資源
if(null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//釋放連接
getMethod.releaseConnection();
}
return result;
}
/**
* POST 請求方法
* @param url
* @param paramMap
* @return
* @throws UnsupportedEncodingException
*/
public static String doPost(String url, Map<String,Object> paramMap) throws UnsupportedEncodingException {
//獲取輸入流
InputStream is = null;
BufferedReader br = null;
String result = null;
//創(chuàng)建httpClient實(shí)例對象
HttpClient httpClient = new HttpClient();
//設(shè)置httpClient連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
//創(chuàng)建post請求方法實(shí)例對象
PostMethod postMethod = new PostMethod(url);
//設(shè)置post請求超時(shí)時(shí)間
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
NameValuePair[] nvp = null;
//判斷參數(shù)map集合paramMap是否為空
if(null != paramMap && paramMap.size() > 0) {//不為空
//創(chuàng)建鍵值參數(shù)對象數(shù)組,大小為參數(shù)的個(gè)數(shù)
nvp = new NameValuePair[paramMap.size()];
//循環(huán)遍歷參數(shù)集合map
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
//獲取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
int index = 0;
while(iterator.hasNext()) {
Entry<String, Object> mapEntry = iterator.next();
//從mapEntry中獲取key和value創(chuàng)建鍵值對象存放到數(shù)組中
nvp[index] = new NameValuePair(mapEntry.getKey(), new String(mapEntry.getValue().toString().getBytes("UTF-8"),"UTF-8"));
index++;
}
}
//判斷nvp數(shù)組是否為空
if(null != nvp && nvp.length > 0) {
//將參數(shù)存放到requestBody對象中
postMethod.setRequestBody(nvp);
}
try {
//執(zhí)行POST方法
int statusCode = httpClient.executeMethod(postMethod);
//判斷是否成功
if(statusCode != HttpStatus.SC_OK) {
System.err.println("Method faild: " + postMethod.getStatusLine());
}
//獲取遠(yuǎn)程返回的數(shù)據(jù)
is = postMethod.getResponseBodyAsStream();
//封裝輸入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
} catch (Exception e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} finally {
//關(guān)閉資源
if(null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//釋放連接
postMethod.releaseConnection();
}
return result;
}
HttpClient 4.5
⒈ 添加依賴
<!-- httpclient4.5版本 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
⒉ 代碼實(shí)現(xiàn)
/**
* Get 請求方法
*
* @param url
* @return
*/
public static String doGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
//通過址默認(rèn)配置創(chuàng)建一個(gè)httpClient實(shí)例
httpClient = HttpClients.createDefault();
//創(chuàng)建httpGet遠(yuǎn)程連接實(shí)例
HttpGet httpGet = new HttpGet(url);
//設(shè)置配置請求參數(shù)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(35000)//連接主機(jī)服務(wù)超時(shí)時(shí)間
.setConnectionRequestTimeout(35000)//請求超時(shí)時(shí)間
.setSocketTimeout(60000)//數(shù)據(jù)讀取超時(shí)時(shí)間
.build();
//為httpGet實(shí)例設(shè)置配置
httpGet.setConfig(requestConfig);
//執(zhí)行g(shù)et請求得到返回對象
response = httpClient.execute(httpGet);
//通過返回對象獲取返回?cái)?shù)據(jù)
HttpEntity entity = response.getEntity();
//通過EntityUtils中的toString方法將結(jié)果轉(zhuǎn)換為字符串
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
//關(guān)閉資源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String doPost(String url, Map<String, Object> paramMap) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
//創(chuàng)建httpClient實(shí)例
httpClient = HttpClients.createDefault();
//創(chuàng)建httpPost遠(yuǎn)程連接實(shí)例
HttpPost httpPost = new HttpPost(url);
//配置請求參數(shù)實(shí)例
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(35000)//設(shè)置連接主機(jī)服務(wù)超時(shí)時(shí)間
.setConnectionRequestTimeout(35000)//設(shè)置連接請求超時(shí)時(shí)間
.setSocketTimeout(60000)//設(shè)置讀取數(shù)據(jù)連接超時(shí)時(shí)間
.build();
//為httpPost實(shí)例設(shè)置配置
httpPost.setConfig(requestConfig);
//封裝post請求參數(shù)
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//通過map集成entrySet方法獲取entity
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
//循環(huán)遍歷,獲取迭代器
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, Object> mapEntry = iterator.next();
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
//為httpPost設(shè)置封裝好的請求參數(shù)
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
//執(zhí)行post請求得到返回對象
response = httpClient.execute(httpPost);
//通過返回對象獲取數(shù)據(jù)
HttpEntity entity = response.getEntity();
//將返回的數(shù)據(jù)轉(zhuǎn)換為字符串
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
//關(guān)閉資源
if (null != response) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}