评论

收藏

[Java] 详解Java发送HTTP请求

编程语言 编程语言 发布于:2021-08-17 13:09 | 阅读数:329 | 评论:0

前言
请求http的demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。
正文
使用须知
为了避免大家引错包我把依赖和涉及到包路径给大家
import java.net.httpurlconnection;
import java.net.uri;
 
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.utils.uribuilder;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
 
 
import com.fasterxml.jackson.databind.objectmapper;
<dependency>
       <groupid>org.apache.httpcomponents</groupid>
       <artifactid>httpcore</artifactid>
       <version>4.4.8</version>
     </dependency>
     <dependency>
       <groupid>org.apache.httpcomponents</groupid>
       <artifactid>httpclient</artifactid>
       <version>4.5.3</version>
     </dependency>
http 发送 get 请求
首先我们引入两个包
发送get请求的工具类,可直接 copy 使用即可
另外,我抛出异常的代码大家改成自己业务的异常,不需要就删除掉。
参数说明:
host:ip
servuri:url
restring:参数
public static string gethttpdata(string host, string servuri, string restring) throws exception {
    stringbuffer sb = new stringbuffer();
    sb.append("gethttpdata:host:" + host + ",servuri:" + servuri + ",restring:" + restring);
    string strresp = null;
    try {
      uri uri = new uribuilder().setscheme("http").sethost(host).setpath(servuri)
          .setparameter("strinfo", restring).build();
      httpget httpget = new httpget(uri);
      closeablehttpclient client3 = httpclients.createdefault();
      httpresponse resp;
      resp = client3.execute(httpget);
      if (resp.getstatusline().getstatuscode() == httpurlconnection.http_ok) {
        strresp = entityutils.tostring(resp.getentity());
        logger.info("the return result:{}", strresp);
      } else {
        logger.info("error response:", resp.getstatusline().tostring());
        throw new commonbusinessexception(commonconstants.task_release_wcf,
            commonconstants.task_release_wcf_desc);
      }
    } catch (exception e) {
      logger.error(sb.tostring() + ":" + e.getmessage(), e.getcause());
      throw new commonbusinessexception(commonconstants.task_release_wcf, commonconstants.task_release_wcf_desc);
    }
    return strresp;
  }
http 发送 post 请求
发送post分两种,我分两种的原因是为了让大家方便,想传对象和 json 可以直接复制过用就可以用,不用你们在转了。
第一种是直接接收json
参数明说:
url:url
json:参数
public static string dopostdata(string url, string json) throws exception {
    defaulthttpclient client = new defaulthttpclient();
    httppost post = new httppost(url);
    string result = "";
    httpresponse res = null;
    try {
      stringentity s = new stringentity(json.tostring(), "utf-8");
      s.setcontenttype("application/json");
      post.setheader("accept", "application/json");
      post.setheader("content-type", "application/json; charset=utf-8");
      post.setentity(s);
      res = client.execute(post);
      if (res.getstatusline().getstatuscode() == httpstatus.sc_ok) {
        result = entityutils.tostring(res.getentity());
        return httpstatus.sc_ok + "";
      }
    } catch (exception e) {
      if(res == null) {
        return "httpresponse 为 null!";
      }
      throw new runtimeexception(e);
    }
    if(res == null || res.getstatusline() == null) {
      return "无响应";
    }
    return res.getstatusline().getstatuscode() + "";
  }
@test
  public void test12() throws exception {
  string host = "http://eipwcf.aspirecn.com/svcef/service1.svc/wcf_ef_msa_getdatainfo_p";
  httpclient client = new httpclient();
  jsonobject json = new jsonobject();
  json.put("msgid", msgid);
  string reslut=client.dopostdata(host, json);
  }
第二种是参数是对象
参数说明:
url:url
tram:对象
public static string dohttppostdata(string url, taskreleaseapprovalmodel tram)
      throws exception {
    stringbuffer sb = new stringbuffer();
    sb.append("dohttppostdata:url:" + url + ",tram:" + tram.tostring() + ",contenttype:" + contenttype);
    logger.info(sb.tostring());
    string tmpstring = "";
    httppost request = new httppost(url);
    request.setheader("accept", "application/json");
    request.setheader("content-type", "application/json");
    objectmapper mapper = new objectmapper();
    string jsonstring;
    try {
      jsonstring = mapper.writevalueasstring(tram);
      stringentity entity = new stringentity(jsonstring, "utf-8");
      request.setentity(entity);
      closeablehttpclient client = httpclients.createdefault();
      httpresponse response = client.execute(request);
      if (response.getstatusline().getstatuscode() == httpurlconnection.http_ok) {
        tmpstring = entityutils.tostring(response.getentity());
        logger.info("the post result:tmpstring:{}", tmpstring);
      } else {
        logger.info("the post failure:tmpstring:", tmpstring);
        throw new commonbusinessexception(commonconstants.task_release_wcf,
            commonconstants.task_release_wcf_desc);
      }
    } catch (exception e) {
      logger.error(sb.tostring() + ":" + e.getmessage(), e.getcause());
      throw new commonbusinessexception(commonconstants.task_release_postwcf,
          commonconstants.task_release_postwcf_desc);
    }
    return tmpstring;
  }
这个方法我想不用写测试类大家也会用,传过去对象和地址就可以了,很方便很简单。
以上所述是小编给大家介绍的java发送http请求详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对CodeAE代码之家网站的支持!

关注下面的标签,发现更多相似文章