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

详解java实现HTTP请求的三种方式

程序员文章站 2023-12-10 17:23:22
目前java实现http请求的方法用的最多的有两种:一种是通过httpclient这种第三方的开源框架去实现。httpclient对http的封装性比较不错,通过它基本上能...

目前java实现http请求的方法用的最多的有两种:一种是通过httpclient这种第三方的开源框架去实现。httpclient对http的封装性比较不错,通过它基本上能够满足我们大部分的需求,httpclient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpclient3.1的代码还是很多,httpclient4.5是org.apache.http.client下操作远程 url的工具包,最新的;另一种则是通过httpurlconnection去实现,httpurlconnection是java的标准类,是java比较原生的一种实现方式。

自己在工作中三种方式都用到过,总结一下分享给大家,也方便自己以后使用,话不多说上代码。

第一种方式:java原生httpurlconnection

package com.powerx.httpclient;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.url;

public class httpclient {
  public static string doget(string httpurl) {
    httpurlconnection connection = null;
    inputstream is = null;
    bufferedreader br = null;
    string result = null;// 返回结果字符串
    try {
      // 创建远程url连接对象
      url url = new url(httpurl);
      // 通过远程url连接对象打开一个连接,强转成httpurlconnection类
      connection = (httpurlconnection) url.openconnection();
      // 设置连接方式:get
      connection.setrequestmethod("get");
      // 设置连接主机服务器的超时时间:15000毫秒
      connection.setconnecttimeout(15000);
      // 设置读取远程返回的数据时间:60000毫秒
      connection.setreadtimeout(60000);
      // 发送请求
      connection.connect();
      // 通过connection连接,获取输入流
      if (connection.getresponsecode() == 200) {
        is = connection.getinputstream();
        // 封装输入流is,并指定字符集
        br = new bufferedreader(new inputstreamreader(is, "utf-8"));
        // 存放数据
        stringbuffer sbf = new stringbuffer();
        string temp = null;
        while ((temp = br.readline()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.tostring();
      }
    } catch (malformedurlexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }

      connection.disconnect();// 关闭远程连接
    }

    return result;
  }

  public static string dopost(string httpurl, string param) {

    httpurlconnection connection = null;
    inputstream is = null;
    outputstream os = null;
    bufferedreader br = null;
    string result = null;
    try {
      url url = new url(httpurl);
      // 通过远程url连接对象打开连接
      connection = (httpurlconnection) url.openconnection();
      // 设置连接请求方式
      connection.setrequestmethod("post");
      // 设置连接主机服务器超时时间:15000毫秒
      connection.setconnecttimeout(15000);
      // 设置读取主机服务器返回数据超时时间:60000毫秒
      connection.setreadtimeout(60000);

      // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
      connection.setdooutput(true);
      // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
      connection.setdoinput(true);
      // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
      connection.setrequestproperty("content-type", "application/x-www-form-urlencoded");
      // 设置鉴权信息:authorization: bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setrequestproperty("authorization", "bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 通过连接对象获取一个输出流
      os = connection.getoutputstream();
      // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
      os.write(param.getbytes());
      // 通过连接对象获取一个输入流,向远程读取
      if (connection.getresponsecode() == 200) {

        is = connection.getinputstream();
        // 对输入流对象进行包装:charset根据工作项目组的要求来设置
        br = new bufferedreader(new inputstreamreader(is, "utf-8"));

        stringbuffer sbf = new stringbuffer();
        string temp = null;
        // 循环遍历一行一行读取数据
        while ((temp = br.readline()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.tostring();
      }
    } catch (malformedurlexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      // 断开与远程地址url的连接
      connection.disconnect();
    }
    return result;
  }
}

第二种方式:apache httpclient3.1

package com.powerx.httpclient;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.unsupportedencodingexception;
import java.util.iterator;
import java.util.map;
import java.util.map.entry;
import java.util.set;

import org.apache.commons.httpclient.defaulthttpmethodretryhandler;
import org.apache.commons.httpclient.httpclient;
import org.apache.commons.httpclient.httpstatus;
import org.apache.commons.httpclient.namevaluepair;
import org.apache.commons.httpclient.methods.getmethod;
import org.apache.commons.httpclient.methods.postmethod;
import org.apache.commons.httpclient.params.httpmethodparams;

public class httpclient3 {

  public static string doget(string url) {
    // 输入流
    inputstream is = null;
    bufferedreader br = null;
    string result = null;
    // 创建httpclient实例
    httpclient httpclient = new httpclient();
    // 设置http连接主机服务超时时间:15000毫秒
    // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
    httpclient.gethttpconnectionmanager().getparams().setconnectiontimeout(15000);
    // 创建一个get方法实例对象
    getmethod getmethod = new getmethod(url);
    // 设置get请求超时为60000毫秒
    getmethod.getparams().setparameter(httpmethodparams.so_timeout, 60000);
    // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
    getmethod.getparams().setparameter(httpmethodparams.retry_handler, new defaulthttpmethodretryhandler(3, true));
    try {
      // 执行get方法
      int statuscode = httpclient.executemethod(getmethod);
      // 判断返回码
      if (statuscode != httpstatus.sc_ok) {
        // 如果状态码返回的不是ok,说明失败了,打印错误信息
        system.err.println("method faild: " + getmethod.getstatusline());
      } else {
        // 通过getmethod实例,获取远程的一个输入流
        is = getmethod.getresponsebodyasstream();
        // 包装输入流
        br = new bufferedreader(new inputstreamreader(is, "utf-8"));

        stringbuffer sbf = new stringbuffer();
        // 读取封装的输入流
        string temp = null;
        while ((temp = br.readline()) != null) {
          sbf.append(temp).append("\r\n");
        }

        result = sbf.tostring();
      }

    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      // 释放连接
      getmethod.releaseconnection();
    }
    return result;
  }

  public static string dopost(string url, map<string, object> parammap) {
    // 获取输入流
    inputstream is = null;
    bufferedreader br = null;
    string result = null;
    // 创建httpclient实例对象
    httpclient httpclient = new httpclient();
    // 设置httpclient连接主机服务器超时时间:15000毫秒
    httpclient.gethttpconnectionmanager().getparams().setconnectiontimeout(15000);
    // 创建post请求方法实例对象
    postmethod postmethod = new postmethod(url);
    // 设置post请求超时时间
    postmethod.getparams().setparameter(httpmethodparams.so_timeout, 60000);

    namevaluepair[] nvp = null;
    // 判断参数map集合parammap是否为空
    if (null != parammap && parammap.size() > 0) {// 不为空
      // 创建键值参数对象数组,大小为参数的个数
      nvp = new namevaluepair[parammap.size()];
      // 循环遍历参数集合map
      set<entry<string, object>> entryset = parammap.entryset();
      // 获取迭代器
      iterator<entry<string, object>> iterator = entryset.iterator();

      int index = 0;
      while (iterator.hasnext()) {
        entry<string, object> mapentry = iterator.next();
        // 从mapentry中获取key和value创建键值对象存放到数组中
        try {
          nvp[index] = new namevaluepair(mapentry.getkey(),
              new string(mapentry.getvalue().tostring().getbytes("utf-8"), "utf-8"));
        } catch (unsupportedencodingexception e) {
          e.printstacktrace();
        }
        index++;
      }
    }
    // 判断nvp数组是否为空
    if (null != nvp && nvp.length > 0) {
      // 将参数存放到requestbody对象中
      postmethod.setrequestbody(nvp);
    }
    // 执行post方法
    try {
      int statuscode = httpclient.executemethod(postmethod);
      // 判断是否成功
      if (statuscode != httpstatus.sc_ok) {
        system.err.println("method faild: " + postmethod.getstatusline());
      }
      // 获取远程返回的数据
      is = postmethod.getresponsebodyasstream();
      // 封装输入流
      br = new bufferedreader(new inputstreamreader(is, "utf-8"));

      stringbuffer sbf = new stringbuffer();
      string temp = null;
      while ((temp = br.readline()) != null) {
        sbf.append(temp).append("\r\n");
      }

      result = sbf.tostring();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      // 释放连接
      postmethod.releaseconnection();
    }
    return result;
  }
}

第三种方式:apache  httpclient4.5

package com.powerx.httpclient;

import java.io.ioexception;
import java.io.unsupportedencodingexception;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;
import java.util.map;
import java.util.map.entry;
import java.util.set;

import org.apache.http.httpentity;
import org.apache.http.namevaluepair;
import org.apache.http.client.clientprotocolexception;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.entity.urlencodedformentity;
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.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.util.entityutils;

public class httpclient4 {

  public static string doget(string url) {
    closeablehttpclient httpclient = null;
    closeablehttpresponse response = null;
    string result = "";
    try {
      // 通过址默认配置创建一个httpclient实例
      httpclient = httpclients.createdefault();
      // 创建httpget远程连接实例
      httpget httpget = new httpget(url);
      // 设置请求头信息,鉴权
      httpget.setheader("authorization", "bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      // 设置配置请求参数
      requestconfig requestconfig = requestconfig.custom().setconnecttimeout(35000)// 连接主机服务超时时间
          .setconnectionrequesttimeout(35000)// 请求超时时间
          .setsockettimeout(60000)// 数据读取超时时间
          .build();
      // 为httpget实例设置配置
      httpget.setconfig(requestconfig);
      // 执行get请求得到返回对象
      response = httpclient.execute(httpget);
      // 通过返回对象获取返回数据
      httpentity entity = response.getentity();
      // 通过entityutils中的tostring方法将结果转换为字符串
      result = entityutils.tostring(entity);
    } catch (clientprotocolexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != response) {
        try {
          response.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != httpclient) {
        try {
          httpclient.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
    return result;
  }

  public static string dopost(string url, map<string, object> parammap) {
    closeablehttpclient httpclient = null;
    closeablehttpresponse httpresponse = null;
    string result = "";
    // 创建httpclient实例
    httpclient = httpclients.createdefault();
    // 创建httppost远程连接实例
    httppost httppost = new httppost(url);
    // 配置请求参数实例
    requestconfig requestconfig = requestconfig.custom().setconnecttimeout(35000)// 设置连接主机服务超时时间
        .setconnectionrequesttimeout(35000)// 设置连接请求超时时间
        .setsockettimeout(60000)// 设置读取数据连接超时时间
        .build();
    // 为httppost实例设置配置
    httppost.setconfig(requestconfig);
    // 设置请求头
    httppost.addheader("content-type", "application/x-www-form-urlencoded");
    // 封装post请求参数
    if (null != parammap && parammap.size() > 0) {
      list<namevaluepair> nvps = new arraylist<namevaluepair>();
      // 通过map集成entryset方法获取entity
      set<entry<string, object>> entryset = parammap.entryset();
      // 循环遍历,获取迭代器
      iterator<entry<string, object>> iterator = entryset.iterator();
      while (iterator.hasnext()) {
        entry<string, object> mapentry = iterator.next();
        nvps.add(new basicnamevaluepair(mapentry.getkey(), mapentry.getvalue().tostring()));
      }

      // 为httppost设置封装好的请求参数
      try {
        httppost.setentity(new urlencodedformentity(nvps, "utf-8"));
      } catch (unsupportedencodingexception e) {
        e.printstacktrace();
      }
    }
    try {
      // httpclient对象执行post请求,并返回响应参数对象
      httpresponse = httpclient.execute(httppost);
      // 从响应对象中获取响应内容
      httpentity entity = httpresponse.getentity();
      result = entityutils.tostring(entity);
    } catch (clientprotocolexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      // 关闭资源
      if (null != httpresponse) {
        try {
          httpresponse.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (null != httpclient) {
        try {
          httpclient.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
    return result;
  }
}

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpclient4.5为例,更改下面两列配置:httppost.setentity(new stringentity("你的json串"));      httppost.addheader("content-type", "application/json")。

以上所述是小编给大家介绍的java实现http请求的三种方式详解整合,希望对大家有所帮助