Java實現(xiàn)Http工具類的封裝操作示例
本文實例講述了Java實現(xiàn)Http工具類的封裝操作。分享給大家供大家參考,具體如下:
http工具類的實現(xiàn):(通過apache包)第一個類
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import com.gooagoo.stcu.utils.http.HttpClientUtils;
public class HTTPRequest {
private String errorMessage; // 錯誤信息
/**
* HTTP請求字符串資源
*
* @param url
* URL地址
* @return 字符串資源
* */
public String httpRequestString(String url) {
String result = null;
try {
HttpEntity httpEntity = httpRequest(url);
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity, "urf-8"); // 使用UTF-8編碼
}
} catch (IOException e) {
errorMessage = e.getMessage();
}
return result;
}
/**
* HTTP請求字節(jié)數(shù)組資源
*
* @param url
* URL地址
* @return 字節(jié)數(shù)組資源
* */
public byte[] httpRequestByteArray(String url) {
byte[] result = null;
try {
HttpEntity httpEntity = httpRequest(url);
if (httpEntity != null) {
result = EntityUtils.toByteArray(httpEntity);
}
} catch (IOException e) {
errorMessage = e.getMessage();
}
return result;
}
/**
* 使用HTTP GET方式請求
*
* @param url
* URL地址
* @return HttpEntiry對象
* */
private HttpEntity httpRequest(String url) {
HttpEntity result = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = HttpClientUtils.getHttpClient();
HttpResponse httpResponse;
httpResponse = httpClient.execute(httpGet);
int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
/*
* 判斷HTTP狀態(tài)碼是否為200
*/
if (httpStatusCode == HttpStatus.SC_OK) {
result = httpResponse.getEntity();
} else {
errorMessage = "HTTP: " + httpStatusCode;
}
} catch (ClientProtocolException e) {
errorMessage = e.getMessage();
} catch (IOException e) {
errorMessage = e.getMessage();
}
return result;
}
/**
* 返回錯誤消息
*
* @return 錯誤信息
* */
public String getErrorMessage() {
return this.errorMessage;
}
}
第二個類的實現(xiàn):
package com.demo.http;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
private static final int REQUEST_TIMEOUT = 5 * 1000;// 設置請求超時10秒鐘
private static final int SO_TIMEOUT = 10 * 1000; // 設置等待數(shù)據(jù)超時時間10秒鐘
// static ParseXml parseXML = new ParseXml();
// 初始化HttpClient,并設置超時
public static HttpClient getHttpClient() {
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
public static boolean doPost(String url) throws Exception {
HttpClient client = getHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response;
response = client.execute(httppost);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
return true;
}
client.getConnectionManager().shutdown();
return false;
}
/**
* 與遠程交互的返回值post方式
*
* @param hashMap
* @param url
* @return
*/
public static String getHttpXml(HashMap<String, String> hashMap, String url) {
String responseMsg = "";
HttpPost request = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> iter = hashMap.entrySet()
.iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpClient client = HttpClientUtils.getHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
responseMsg = EntityUtils.toString(response.getEntity());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responseMsg;
}
/**
* map轉字符串 拼接參數(shù)
*
* @param hashMap
* @return
*/
public static String mapToString(HashMap<String, String> hashMap) {
String parameStr = "";
Iterator<Map.Entry<String, String>> iter = hashMap.entrySet()
.iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
parameStr += "&" + entry.getKey() + "=" + entry.getValue();
}
if (parameStr.contains("&")) {
parameStr = parameStr.replaceFirst("&", "?");
}
return parameStr;
}
}
更多關于java相關內(nèi)容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
mybatis-plus @DS實現(xiàn)動態(tài)切換數(shù)據(jù)源原理
本文主要介紹了mybatis-plus @DS實現(xiàn)動態(tài)切換數(shù)據(jù)源原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
如何解決Project SDK is not defined問題
這篇文章主要介紹了如何解決Project SDK is not defined問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Maven編譯錯誤:程序包com.sun.*包不存在的三種解決方案
J2SE中的類大致可以劃分為以下的各個包:java.*,javax.*,org.*,sun.*,本文文章主要介紹了maven編譯錯誤:程序包com.sun.xml.internal.ws.spi不存在的解決方案,感興趣的可以了解一下2024-02-02
springboot項目組引入JMeter的實現(xiàn)步驟
本文主要介紹了springboot項目組引入JMeter的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

