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

Java http請求封裝工具類代碼實例

 更新時間:2020年04月23日 11:12:58   作者:gdjlc  
這篇文章主要介紹了Java http請求封裝工具類代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

java實現(xiàn)http請求的方法常用有兩種,一種則是通過java自帶的標(biāo)準(zhǔn)類HttpURLConnection去實現(xiàn),另一種是通過apache的httpclient去實現(xiàn)。

本文用httpclient去實現(xiàn),需要導(dǎo)入httpclient和httpcore兩個jar包,測試時用的httpclient-4.5.1和httpcore-4.4.3。

HttpMethod.java

package demo;
public enum HttpMethod {
  GET, POST;
}

HttpHeader.java

package demo;

import java.util.HashMap;
import java.util.Map;

/**
 * 請求頭
 */
public class HttpHeader {
  private Map<String, String> params = new HashMap<String, String>();
    
  public HttpHeader addParam(String name, String value) {
    this.params.put(name, value);
    return this;
  }
  
  public Map<String, String> getParams() {
    return this.params;
  }
}

HttpParamers.java

package demo;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;

/**
 * 請求參數(shù)
 */
public class HttpParamers {
  private Map<String, String> params = new HashMap<String, String>();
  private HttpMethod httpMethod;
  private String jsonParamer = "";

  public HttpParamers(HttpMethod httpMethod) {
    this.httpMethod = httpMethod;
  }

  public static HttpParamers httpPostParamers() {
    return new HttpParamers(HttpMethod.POST);
  }

  public static HttpParamers httpGetParamers() {
    return new HttpParamers(HttpMethod.GET);
  }
  
  public HttpParamers addParam(String name, String value) {
    this.params.put(name, value);
    return this;
  }

  public HttpMethod getHttpMethod() {
    return this.httpMethod;
  }

  public String getQueryString(String charset) throws IOException {
    if ((this.params == null) || (this.params.isEmpty())) {
      return null;
    }
    StringBuilder query = new StringBuilder();
    Set<Map.Entry<String, String>> entries = this.params.entrySet();

    for (Map.Entry<String, String> entry : entries) {
      String name = entry.getKey();
      String value = entry.getValue();
      query.append("&").append(name).append("=").append(URLEncoder.encode(value, charset));
    }
    return query.substring(1);
  }

  public boolean isJson() {
    return !isEmpty(this.jsonParamer);
  }

  public Map<String, String> getParams() {
    return this.params;
  }

  public String toString() {
    return "HttpParamers " + JSON.toJSONString(this);    
  }

  public String getJsonParamer() {
    return this.jsonParamer;
  }
  
  public void setJsonParamer() {
    this.jsonParamer = JSON.toJSONString(this.params);
  }
  
  private static boolean isEmpty(CharSequence cs) {
    return (cs == null) || (cs.length() == 0);
  }
}

HttpClient.java

package demo;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClient {
  public static final String DEFAULT_CHARSET = "UTF-8";
  public static final String JSON_CONTENT_FORM = "application/json;charset=UTF-8";
  public static final String CONTENT_FORM = "application/x-www-form-urlencoded;charset=UTF-8";
  
  public static String doService(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws Exception {
    HttpMethod httpMethod = paramers.getHttpMethod();
    switch (httpMethod) {
      case GET:
        return doGet(url, paramers, header, connectTimeout, readTimeout);
      case POST:
        return doPost(url, paramers, header, connectTimeout, readTimeout);
    }
    return null;
  }
  
  /**
   * post方法
   * @param url
   * @param paramers
   * @param header
   * @param connectTimeout
   * @param readTimeout
   * @return
   * @throws IOException
   */
  public static String doPost(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
    String responseData = "";
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;    
    try{
      String query = null;          
      HttpPost httpPost = new HttpPost(url);
      setHeader(httpPost, header);            
      if (paramers.isJson()) {
        //json數(shù)據(jù)
        httpPost.setHeader(HTTP.CONTENT_TYPE, JSON_CONTENT_FORM);        
        query = paramers.getJsonParamer();
      } else {
        //表單數(shù)據(jù)
        httpPost.setHeader(HTTP.CONTENT_TYPE, CONTENT_FORM);
        query = paramers.getQueryString(DEFAULT_CHARSET);
      }
      if(query != null){
        HttpEntity reqEntity = new StringEntity(query);
        httpPost.setEntity(reqEntity);
      }      
      httpClient = HttpClients.createDefault();            
      httpResponse = httpClient.execute(httpPost);
      HttpEntity resEntity = httpResponse.getEntity();
      responseData = EntityUtils.toString(resEntity);
    } catch (Exception e){
      e.printStackTrace();
    } finally{
      httpResponse.close();
      httpClient.close();
    }
    return responseData;
  }
  
  
  /**
   * get方法
   * @param url
   * @param params
   * @param header
   * @param connectTimeout
   * @param readTimeout
   * @return
   * @throws IOException
   */
  public static String doGet(String url, HttpParamers params, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
    String responseData = "";
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;    
    try{  
      String query = params.getQueryString(DEFAULT_CHARSET);  
      url = buildGetUrl(url, query);
      HttpGet httpGet = new HttpGet(url);
      setHeader(httpGet, header);  
      httpClient = HttpClients.createDefault();            
      httpResponse = httpClient.execute(httpGet);
      HttpEntity resEntity = httpResponse.getEntity();
      responseData = EntityUtils.toString(resEntity);
    } catch (Exception e){
      e.printStackTrace();
    } finally{
      httpResponse.close();
      httpClient.close();
    }
    return responseData;
  }
  
  private static void setHeader(HttpRequestBase httpRequestBase, HttpHeader header){
    if(header != null){
      Map<String,String> headerMap = header.getParams();
      if (headerMap != null && !headerMap.isEmpty()) {    
        Set<Map.Entry<String, String>> entries = headerMap.entrySet();  
        for (Map.Entry<String, String> entry : entries) {
          String name = entry.getKey();
          String value = entry.getValue();
          httpRequestBase.setHeader(name, value);
        }
      }
    }
  }
  
  private static String buildGetUrl(String url, String query) throws IOException {
    if (query == null || query.equals("")) {
      return url;
    }
    StringBuilder newUrl = new StringBuilder(url);
    boolean hasQuery = url.contains("?");
    boolean hasPrepend = (url.endsWith("?")) || (url.endsWith("&"));
    if (!hasPrepend) {
      if (hasQuery) {
        newUrl.append("&");
      } else {
        newUrl.append("?");
        hasQuery = true;
      }
    }
    newUrl.append(query);
    hasPrepend = false;
    return newUrl.toString();
  }
}

HttpService.java

package demo;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

public class HttpService {
  private String serverUrl;
  private int connectTimeout = 15000;
  private int readTimeout = 30000;
  public HttpService(String serverUrl) {
    this.serverUrl = serverUrl.trim();
  }
  public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers) throws Exception{
    return commonService(serviceUrl, paramers, null);
  }
  public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception{
    String response = service(serviceUrl, paramers, header);
    try {
      Map<String, Object> result = JSONObject.parseObject(response, new TypeReference<Map<String, Object>>() {});
      if ((result == null) || (result.isEmpty())) {
        throw new Exception("遠(yuǎn)程服務(wù)返回的數(shù)據(jù)無法解析");
      }
      Integer code = (Integer) result.get("code");
      if ((code == null) || (code.intValue() != 0)) {
        throw new Exception((String) result.get("message"));
      }
      return result;
    } catch (Exception e) {
      throw new Exception("返回結(jié)果異常,response:" + response, e);
    }
  }
  public String service(String serviceUrl, HttpParamers paramers) throws Exception {
    return service(serviceUrl, paramers, null);
  }
  public String service(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception {
    String url = this.serverUrl + serviceUrl;
    String responseData = "";
    try {
      responseData = HttpClient.doService(url, paramers, header, this.connectTimeout, this.readTimeout);
    } catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
    return responseData;
  }
  
  public String getServerUrl() {
    return this.serverUrl;
  }

  public int getConnectTimeout() {
    return this.connectTimeout;
  }

  public int getReadTimeout() {
    return this.readTimeout;
  }

  public void setConnectTimeout(int connectTimeout) {
    this.connectTimeout = connectTimeout;
  }

  public void setReadTimeout(int readTimeout) {
    this.readTimeout = readTimeout;
  }
}

測試?yán)覶est1.java

package demo;

import org.junit.Ignore;
import org.junit.Test;

public class Test1 {

  //免費的在線REST服務(wù), 提供測試用的HTTP請求假數(shù)據(jù)
  //接口信息說明可見:http://www.hangge.com/blog/cache/detail_2020.html
  String uri = "http://jsonplaceholder.typicode.com";
  
  //get方式請求數(shù)據(jù)
  //請求地址:http://jsonplaceholder.typicode.com/posts
  @Ignore("暫時忽略")
  @Test
  public void test1() {
    System.out.print("\n" + "test1---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpGetParamers();
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);
      response = httpService.service("/posts", paramers);      
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }
  
  //get方式請求數(shù)據(jù)
  //請求地址:http://jsonplaceholder.typicode.com/posts?userId=5
  @Ignore("暫時忽略")
  @Test
  public void test2() {
    System.out.print("\n" + "test2---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpGetParamers();
    paramers.addParam("userId", "5");
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);      
      response = httpService.service("/posts", paramers);      
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }
  
  //post方式請求數(shù)據(jù)
  //請求地址:http://jsonplaceholder.typicode.com/posts  
  @Test
  public void test3() {
    System.out.print("\n" + "test3---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpPostParamers();
    paramers.addParam("time", String.valueOf(System.currentTimeMillis()));
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);
      response = httpService.service("/posts", paramers);      
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring定時任務(wù)實現(xiàn)與配置(二)

    Spring定時任務(wù)實現(xiàn)與配置(二)

    這篇文章主要為大家詳細(xì)介紹了Spring定時任務(wù)的實現(xiàn)與配置第二篇,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Java實現(xiàn)猜數(shù)字小游戲(有次數(shù)限制)

    Java實現(xiàn)猜數(shù)字小游戲(有次數(shù)限制)

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)猜數(shù)字小游戲,有次數(shù)限制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • Java ArrayDeque使用方法詳解

    Java ArrayDeque使用方法詳解

    這篇文章主要為大家詳細(xì)介紹了Java ArrayDeque的使用方法,感興趣的小伙伴們可以參考一下
    2016-03-03
  • spring?controller層引用service報空指針異常nullpointExceptio問題

    spring?controller層引用service報空指針異常nullpointExceptio問題

    這篇文章主要介紹了spring?controller層引用service報空指針異常nullpointExceptio問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Java 照片對比功能的實現(xiàn)

    Java 照片對比功能的實現(xiàn)

    這篇文章主要介紹了Java 照片比對功能實現(xiàn)類的示例代碼,幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下
    2020-12-12
  • Java中Spock框架Mock對象的方法經(jīng)驗總結(jié)

    Java中Spock框架Mock對象的方法經(jīng)驗總結(jié)

    這篇文章主要分享了Spock框架Mock對象的方法經(jīng)驗總結(jié),下文分享一些常用項目實戰(zhàn)說明以及代碼,供大家項目中參考,也具有一的的參考價值,需要的小伙伴可以參考一下
    2022-02-02
  • Spring中的編程式事務(wù)和聲明式事務(wù)

    Spring中的編程式事務(wù)和聲明式事務(wù)

    Spring框架中,事務(wù)管理可以通過編程式事務(wù)和聲明式事務(wù)兩種方式實現(xiàn),編程式事務(wù)通過手動編碼控制事務(wù)的開始、提交和回滾,允許開發(fā)者精確控制事務(wù),但增加了代碼復(fù)雜度,聲明式事務(wù)則通過@EnableTransactionManagement注解啟用事務(wù)管理
    2024-11-11
  • Spring MVC利用Swagger2如何構(gòu)建動態(tài)RESTful API詳解

    Spring MVC利用Swagger2如何構(gòu)建動態(tài)RESTful API詳解

    這篇文章主要給大家介紹了關(guān)于在Spring MVC中利用Swagger2如何構(gòu)建動態(tài)RESTful API的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • 手動實現(xiàn)將本地jar添加到Maven倉庫

    手動實現(xiàn)將本地jar添加到Maven倉庫

    這篇文章主要介紹了手動實現(xiàn)將本地jar添加到Maven倉庫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • java 對象的序列化和反序列化詳細(xì)介紹

    java 對象的序列化和反序列化詳細(xì)介紹

    這篇文章主要介紹了java 對象的序列化和反序列化的相關(guān)資料,需要的朋友可以參考下
    2016-10-10

最新評論

定陶县| 五峰| 襄汾县| 罗田县| 定安县| 康定县| 福建省| 合肥市| 张家川| 旬阳县| 正镶白旗| 湄潭县| 应用必备| 岳阳市| 乌什县| 四平市| 柳河县| 沅江市| 东源县| 巴林右旗| 威远县| 万山特区| 镇坪县| 卫辉市| 长葛市| 山东| 多伦县| 麻栗坡县| 金塔县| 兴业县| 盐亭县| 佛山市| 茌平县| 泸西县| 安乡县| 喀喇沁旗| 阿坝县| 漳平市| 蛟河市| 嘉鱼县| 林芝县|