最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實(shí)現(xiàn)Http工具類的封裝操作示例

 更新時間:2018年01月06日 12:16:26   作者:記憶沉思  
這篇文章主要介紹了Java實(shí)現(xiàn)Http工具類的封裝操作,涉及java針對http請求與響應(yīng)、遠(yuǎn)程交互與字符串拼接等操作封裝技巧,需要的朋友可以參考下

本文實(shí)例講述了Java實(shí)現(xiàn)Http工具類的封裝操作。分享給大家供大家參考,具體如下:

http工具類的實(shí)現(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;
  }
}

第二個類的實(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è)置請求超時10秒鐘
  private static final int SO_TIMEOUT = 10 * 1000; // 設(shè)置等待數(shù)據(jù)超時時間10秒鐘
  // static ParseXml parseXML = new ParseXml();
  // 初始化HttpClient,并設(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;
  }
}

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結(jié)》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • 輕松掌握J(rèn)ava注解,讓編程更智能、更優(yōu)雅

    輕松掌握J(rèn)ava注解,讓編程更智能、更優(yōu)雅

    輕松掌握J(rèn)ava注解?沒問題!想要讓你的Java代碼更具可讀性、維護(hù)性,同時提升開發(fā)效率?本指南將帶你快速入門Java注解的世界,只需短短幾分鐘,你就能揭秘這個強(qiáng)大的編程工具,讓編寫有聲明性邏輯的代碼變得輕而易舉,趕快一起來探索吧!
    2024-01-01
  • mybatis-plus @DS實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源原理

    mybatis-plus @DS實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源原理

    本文主要介紹了mybatis-plus @DS實(shí)現(xiàn)動態(tài)切換數(shù)據(jù)源原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • Java8 HashMap遍歷方式性能探討

    Java8 HashMap遍歷方式性能探討

    JDK8之前,可以使用keySet或者entrySet來遍歷HashMap,JDK8中引入了map.foreach來進(jìn)行遍歷
    2021-09-09
  • 如何解決Project SDK is not defined問題

    如何解決Project SDK is not defined問題

    這篇文章主要介紹了如何解決Project SDK is not defined問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Maven編譯錯誤:程序包c(diǎn)om.sun.*包不存在的三種解決方案

    Maven編譯錯誤:程序包c(diǎn)om.sun.*包不存在的三種解決方案

    J2SE中的類大致可以劃分為以下的各個包:java.*,javax.*,org.*,sun.*,本文文章主要介紹了maven編譯錯誤:程序包c(diǎn)om.sun.xml.internal.ws.spi不存在的解決方案,感興趣的可以了解一下
    2024-02-02
  • SpringBoot2線程池定義使用方法解析

    SpringBoot2線程池定義使用方法解析

    這篇文章主要介紹了SpringBoot2線程池定義使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • springboot項(xiàng)目組引入JMeter的實(shí)現(xiàn)步驟

    springboot項(xiàng)目組引入JMeter的實(shí)現(xiàn)步驟

    本文主要介紹了springboot項(xiàng)目組引入JMeter的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • SpringDataJpa多表操作的實(shí)現(xiàn)

    SpringDataJpa多表操作的實(shí)現(xiàn)

    開發(fā)過程中會有很多多表的操作,他們之間有著各種關(guān)系,本文主要介紹了SpringDataJpa多表操作的實(shí)現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Java如何使用jar命令打包

    Java如何使用jar命令打包

    把多個文件打包成一個壓縮包——這個壓縮包和WinZip的壓縮格式是一樣的,區(qū)別在于jar壓縮的文件默認(rèn)多一個META-INF的文件夾,該文件夾里包含一個MANIFEST.MF的文件,本文給大家介紹Java如何使用jar命令打包,感興趣的朋友跟隨小編一起看看吧
    2023-10-10
  • Java?Apache?common-pool對象池介紹

    Java?Apache?common-pool對象池介紹

    這篇文章主要介紹了Java Apache?common-pool對象池介紹,文章通過圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下
    2022-09-09

最新評論

丹凤县| 利辛县| 青州市| 烟台市| 道孚县| 弥渡县| 洛阳市| 酉阳| 维西| 勐海县| 宁蒗| 华容县| 高平市| 蒙山县| 图木舒克市| 孟州市| 边坝县| 沂水县| 海晏县| 靖宇县| 南漳县| 武隆县| 海伦市| 怀集县| 华坪县| 沂南县| 九寨沟县| 宿松县| 上思县| 贵港市| 锦屏县| 嵊泗县| 吉水县| 阆中市| 黄浦区| 淮安市| 阿城市| 永顺县| 贺兰县| 墨竹工卡县| 关岭|