Java USES httpclient to send a sample post request

  • 2020-04-01 02:56:54
  • OfStack


package org.ssi.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class APIHttpClient {
 //Address of the interface
 private String apiURL = "";
 private Log logger = LogFactory.getLog(this.getClass());
 private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
        private HttpClient httpClient = null;
 private HttpPost method = null;
 private long startTime = 0L;
 private long endTime = 0L;
 private int status = 0;
 
 public APIHttpClient(String url){
  if(url != null)
  {
   this.apiURL = url;
  }
  if(apiURL != null)
  {
                    httpClient = new DefaultHttpClient();
                    method = new HttpPost(apiURL);

  }
 }

 
 public String post(String parameters)
 {
  String body = null;
                logger.info("parameters:" + parameters);

                
  if(method != null & parameters != null  && !"".equals(parameters.trim()))
  {
                    JSONArray jsonObject = JSONArray.fromObject(parameters);
                    logger.info("json:" + jsonObject.toString());
                    try{
                        List<NameValuePair> params=new ArrayList<NameValuePair>();  
                        //Creates a NameValuePair array to store the parameters to be passed.
                        params.add(new BasicNameValuePair("data",parameters));  
                        //Add parameter & NBSP;
                        method.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  

                        startTime = System.currentTimeMillis();

                        //Setting the code & NBSP;
                        HttpResponse response=httpClient.execute(method);  
                        endTime = System.currentTimeMillis();
                        int statusCode = response.getStatusLine().getStatusCode();
                        logger.info("statusCode:" + statusCode);
                         logger.info(" call API  Spend time ( Units: milliseconds ) : " + (endTime - startTime));
                        if(statusCode != HttpStatus.SC_OK){
                            logger.error("Method failed:"+response.getStatusLine());
                            status = 1;
                        }

                            //Read the response body
                             body=EntityUtils.toString(response.getEntity()); 

   }catch(IOException e){
    //Network anomaly
    logger.error("exception occurred!n"+ExceptionUtils.getFullStackTrace(e));
    //Network error
    status = 3;
   }
                    finally{
                        logger.info(" State of calling interface: " + status);
                    }

   
  }
  return body;
 }
 
 public int getStatus() {
  return status;
 }
 
 public void setStatus(int status) {
  this.status = status;
 }
 
 public long getStartTime() {
  return startTime;
 }
 
 public long getEndTime() {
  return endTime;
 }
}


Related articles: