服务器之家

服务器之家 > 正文

Java实现Http工具类的封装操作示例

时间:2021-03-16 10:56     来源/作者:记忆沉思

本文实例讲述了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

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部