Java USES HttpClient to implement Post request instances

  • 2020-06-12 08:57:26
  • OfStack

Based on the project requirements, we want to implement Post message push, so we use HttpClient component for implementation, and the relevant code is as follows (note: the version of httpclient and httpcore dependent packages adopted by the program is 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();

    //  Set the timeout 
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
      
    post = new HttpPost(url);
    //  Construct message header 
    post.setHeader("Content-type", "application/json; charset=utf-8");
    post.setHeader("Connection", "Close");
    String sessionId = getSessionId();
    post.setHeader("SessionId", sessionId);
    post.setHeader("appid", appid);
          
    //  Build the message entity 
    StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
    entity.setContentEncoding("UTF-8");
    //  send Json Data request in format 
    entity.setContentType("application/json");
    post.setEntity(entity);
      
    HttpResponse response = httpClient.execute(post);
      
    //  Check return code 
    int statusCode = response.getStatusLine().getStatusCode();
    if(statusCode != HttpStatus.SC_OK){
      LogUtil.info(" Request error : "+statusCode);
      isSuccess = false;
    }else{
      int retCode = 0;
      String sessendId = "";
      //  The return code contains retCode And speaking 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 ){
        //  Log print 
        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;
}

//  Build only 1 The session 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: "java. lang. NoSuchFieldError: INSTANCE" when sending POST requests using the Hadoop cluster. This problem is usually caused by "jar packet conflicts", but the strange thing is that the local ES17en. xml set the dependency packet with this field.


<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>  

Then on the Internet for 1 turn, find out the cause of the problem, the reason is that Hadoop cluster to run the program, the first loads related directory jar package, in his own directory if not found, will be specified jar loader runtime package, with the lookup Hadoop cluster related Jar package path, find httpclient related dependent package for 4.2.5, will therefore pom. xml configuration file also update to this version, is run through the program.


Related articles: