您好,登錄后才能下訂單哦!
怎么在Java中實(shí)現(xiàn)一個(gè)Http工具類?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
http工具類的實(shí)現(xiàn):(通過apache包)第一個(gè)類
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; // 錯(cuò)誤信息 /** * HTTP請(qǐng)求字符串資源 * * @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請(qǐng)求字節(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方式請(qǐng)求 * * @param url * URL地址 * @return HttpEntiry對(duì)象 * */ 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; } /** * 返回錯(cuò)誤消息 * * @return 錯(cuò)誤信息 * */ public String getErrorMessage() { return this.errorMessage; } }
第二個(gè)類的實(shí)現(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;// 設(shè)置請(qǐng)求超時(shí)10秒鐘 private static final int SO_TIMEOUT = 10 * 1000; // 設(shè)置等待數(shù)據(jù)超時(shí)時(shí)間10秒鐘 // static ParseXml parseXML = new ParseXml(); // 初始化HttpClient,并設(shè)置超時(shí) 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; } /** * 與遠(yuǎn)程交互的返回值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轉(zhuǎn)字符串 拼接參數(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; } }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。