Java uses httpclient to send a POST request sample _java

Source: Internet
Author: User

Copy Code code as follows:

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 {

Interface Address
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;
/**
* Interface Address
* @param URL
*/
Public apihttpclient (String URL) {

if (URL!= null)
{
This.apiurl = URL;
}
if (Apiurl!= null)
{
HttpClient = new Defaulthttpclient ();
method = new HttpPost (Apiurl);

}
}

/**
* Calling API
* @param parameters
* @return
*/
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> ();
Create a Namevaluepair array to store the parameters to be transmitted
Params.add (New Basicnamevaluepair ("Data", parameters));
Add parameters
Method.setentity (New Urlencodedformentity (params,http). Utf_8));

StartTime = System.currenttimemillis ();

Set encoding
HttpResponse Response=httpclient.execute (method);
Endtime = System.currenttimemillis ();
int statusCode = Response.getstatusline (). Getstatuscode ();
Logger.info ("StatusCode:" + statusCode);
Logger.info ("Invoke API takes time (in 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) {
A network exception occurred
Logger.error ("Exception occurred!\n" +exceptionutils.getfullstacktrace (e));
Network error
status = 3;
}
finally{
Logger.info ("Invoke Interface State:" + status);
}


}
return to body;
}

/**
* 0. Success 1. Execution method failure 2. Protocol error 3. Network error
* @return The status
*/
public int GetStatus () {
return status;
}

/**
* @param status The status to set
*/
public void setstatus (int status) {
This.status = status;
}
/**
* @return The StartTime
*/
Public long GetStartTime () {
return starttime;
}
/**
* @return The Endtime
*/
Public long Getendtime () {
return endtime;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.