欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-26 08:03:58
java实现http请求的方法常用有两种,一种则是通过java自带的标准类httpurlconnection去实现,另一种是通过apache的httpclient去实现。本文用httpclient去实...

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);
  }
}

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