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

Java使用HttpClient实现Post请求实例

程序员文章站 2024-03-06 08:05:31
基于项目需求,想要实现post消息推送,故采用httpclient组件进行实现,相关代码如下(注:程序采用的httpclient和httpcore依赖包的版本为4.2.5)...

基于项目需求,想要实现post消息推送,故采用httpclient组件进行实现,相关代码如下(注:程序采用的httpclient和httpcore依赖包的版本为4.2.5):

import org.apache.http.header;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httppost;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.params.coreconnectionpnames;
import java.util.uuid;
import net.sf.json.jsonobject;
import java.nio.charset.charset;

public static boolean httppostwithjson(jsonobject jsonobj,string url,string appid){
  boolean issuccess = false;
  
  httppost post = null;
  try {
    httpclient httpclient = new defaulthttpclient();

    // 设置超时时间
    httpclient.getparams().setparameter(coreconnectionpnames.connection_timeout, 2000);
    httpclient.getparams().setparameter(coreconnectionpnames.so_timeout, 2000);
      
    post = new httppost(url);
    // 构造消息头
    post.setheader("content-type", "application/json; charset=utf-8");
    post.setheader("connection", "close");
    string sessionid = getsessionid();
    post.setheader("sessionid", sessionid);
    post.setheader("appid", appid);
          
    // 构建消息实体
    stringentity entity = new stringentity(jsonobj.tostring(), charset.forname("utf-8"));
    entity.setcontentencoding("utf-8");
    // 发送json格式的数据请求
    entity.setcontenttype("application/json");
    post.setentity(entity);
      
    httpresponse response = httpclient.execute(post);
      
    // 检验返回码
    int statuscode = response.getstatusline().getstatuscode();
    if(statuscode != httpstatus.sc_ok){
      logutil.info("请求出错: "+statuscode);
      issuccess = false;
    }else{
      int retcode = 0;
      string sessendid = "";
      // 返回码中包含retcode及会话id
      for(header header : response.getallheaders()){
        if(header.getname().equals("retcode")){
          retcode = integer.parseint(header.getvalue());
        }
        if(header.getname().equals("sessionid")){
          sessendid = header.getvalue();
        }
      }
      
      if(errorcodehelper.ias_success != retcode ){
        // 日志打印
        logutil.info("error return code, sessionid: "sessendid"\t"+"retcode: "+retcode);
        issuccess = false;
      }else{
        issuccess = true;
      }
    }
  } catch (exception e) {
    e.printstacktrace();
    issuccess = false;
  }finally{
    if(post != null){
      try {
        post.releaseconnection();
        thread.sleep(500);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
    }
  }
  return issuccess;
}

// 构建唯一会话id
public static string getsessionid(){
  uuid uuid = uuid.randomuuid();
  string str = uuid.tostring();
  return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
}

ps: 在使用hadoop集群进行发送post请求时,遇到"java.lang.nosuchfielderror: instance"的问题,此类问题一般是"jar包冲突"的问题所致,但奇怪的是本地的pom.xml设置的依赖包中有该字段,相关的httpclient依赖包如下:  

<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpclient</artifactid>
  <version>4.4.1</version>
</dependency>
<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpcore</artifactid>
  <version>4.4.1</version>
</dependency>  

随后在网上查找了一翻,找到问题的缘由,原因在于hadoop集群运行程序时,首先会加载自己相关目录下的jar包,在自己目录下如果未找到,才会加载程序运行时指定的jar包,随查找了hadoop集群中相关jar包路径,发现httpclient的相关依赖包为4.2.5,因此将pom.xml配置文件也更新为该版本,程序则运行通过.

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