Java http请求封装工具类代码实例

 更新时间:2020年04月23日 11:12:58   作者:gdjlc  
这篇文章主要介绍了Java http请求封装工具类代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现。

本文用httpclient去实现,需要导入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;

/**
 * 请求参数
 */
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数据
        httpPost.setHeader(HTTP.CONTENT_TYPE, JSON_CONTENT_FORM);        
        query = paramers.getJsonParamer();
      } else {
        //表单数据
        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("远程服务返回的数据无法解析");
      }
      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("返回结果异常,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;
  }
}

测试例子Test1.java

package demo;

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

public class Test1 {

  //免费的在线REST服务, 提供测试用的HTTP请求假数据
  //接口信息说明可见:http://www.hangge.com/blog/cache/detail_2020.html
  String uri = "http://jsonplaceholder.typicode.com";
  
  //get方式请求数据
  //请求地址: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方式请求数据
  //请求地址: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方式请求数据
  //请求地址: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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 详细解读java同步之synchronized解析

    详细解读java同步之synchronized解析

    synchronized关键字是Java里面最基本的同步手段,下面我们来一起学习一下
    2019-05-05
  • Spring boot详解fastjson过滤字段为null值如何解决

    Spring boot详解fastjson过滤字段为null值如何解决

    这篇文章主要介绍了解决Spring boot中fastjson过滤字段为null值的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • linux下用renameTo方法修改java web项目中文件夹名称的实例

    linux下用renameTo方法修改java web项目中文件夹名称的实例

    下面小编就为大家带来一篇linux下用renameTo方法修改java web项目中文件夹名称的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 关于Java中静态代码块的执行浅析

    关于Java中静态代码块的执行浅析

    这篇文章主要给大家介绍了关于Java中静态代码块执行的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-09-09
  • springboot中设置定时任务的三种方法小结

    springboot中设置定时任务的三种方法小结

    在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容,本文介绍了springboot中设置定时任务的三种方法,主要包括@Scheduled注解,Quartz框架和xxl-job框架的实现,感兴趣的可以了解一下
    2023-12-12
  • SpringBoot使用JUL实现日志记录功能

    SpringBoot使用JUL实现日志记录功能

    在SpringBoot中,我们可以使用多种日志框架进行日志记录,其中,JUL(Java Util Logging)是Java平台自带的日志框架,它提供了简单的 API 和配置,可以轻松地进行日志记录,本文将介绍如何在 SpringBoot中使用JUL进行日志记录,并提供示例代码
    2023-06-06
  • Java快速排序的实现方法示例

    Java快速排序的实现方法示例

    快速排序是对冒泡排序的一种改进,下面这篇文章主要给大家介绍了关于Java快速排序的实现方法,文中通过代码介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2024-03-03
  • 学习Java之如何对时间进行格式化

    学习Java之如何对时间进行格式化

    当我们在默认情况下构造出来的时间对象,它的时间格式并不适合我们阅读,并且在开发时,pc端、Android端、iOS端等展示的时间格式可能也并不完全一样,本文就从这几个问题给大家介绍如何对时间进行格式化,感兴趣的同学可以借鉴一下
    2023-05-05
  • 浅谈Servlet 实现网页重定向的方法

    浅谈Servlet 实现网页重定向的方法

    本篇文章主要介绍了Servlet 实现重定向几种方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • Java泛型中<?>和<T>的区别浅析

    Java泛型中<?>和<T>的区别浅析

    <T>和<?>的区别 <T>是参数类型,常常用于泛型类或泛型方法的定义,下面这篇文章主要给大家介绍了关于Java泛型中<?>和<T>区别的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-12-12

最新评论