一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java實現Http工具類的封裝操作示例

Java實現Http工具類的封裝操作示例

2021-03-16 10:56記憶沉思 Java教程

這篇文章主要介紹了Java實現Http工具類的封裝操作,涉及java針對http請求與響應、遠程交互與字符串拼接等操作封裝技巧,需要的朋友可以參考下

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

http工具類的實現:(通過apache包)第一個類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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請求字節數組資源
   *
   * @param url
   *      URL地址
   * @return 字節數組資源
   * */
  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狀態碼是否為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;
  }
}

第二個類的實現:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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; // 設置等待數據超時時間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轉字符串 拼接參數
   *
   * @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程序設計有所幫助。

原文鏈接:http://blog.csdn.net/u012083681/article/details/17512271

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 久久伊人精品青青草原2021 | 啪啪无尽3d动漫漫画免费网站 | 成人综合网址 | 国精视频一区二区视频 | 亚洲欧美精品天堂久久综合一区 | 精品国产一区二区在线观看 | 国产美女久久精品香蕉69 | 国产乱子伦一区二区三区 | 好爽轻点太大了太深了 | 国产图色| 亚洲精品国产福利片 | 美女福利视频一区二区 | 日韩一区在线播放 | 秋霞一级 | 日本海鸣馆 | 四虎在线永久视频观看 | 久久综合给合久久狠狠狠… | 国产自拍视频网站 | 欧美日韩一区二区综合 | 国产成人精品一区二区不卡 | 亚洲精品成人a | fuqer日本 | aaaa黄色片 | 日本高清全集免费观看 | 国产日韩欧美一区 | 惩罚美女妲己的尤老师 | 亚洲 欧美 中文 日韩欧美 | 全黄h全肉细节修仙玄幻文 全彩调教侵犯h本子全彩妖气he | 色综合网天天综合色中文男男 | 午夜影院和视费x看 | 日本高清在线精品一区二区三区 | 欧美第一视频 | 四虎在线精品免费高清在线 | 亚洲尿尿 | 亚洲香蕉视频 | 日本中文字幕在线精品 | 丝瓜草莓香蕉绿巨人幸福宝 | 大肥臀风间由美 中文字幕 大东北chinesexxxx露脸 | 国产在线观看99 | 日韩欧美成末人一区二区三区 | 四虎精品免费国产成人 |