Use Apache HttpClient to Post JSON data

Source: Internet
Author: User

Import Org.apache.commons.io.IOUtils;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.ClientProtocolException;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpClientBuilder;
Import Org.apache.http.message.BasicHeader;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.protocol.HTTP;

Import Com.alibaba.fastjson.JSONObject;


InputStream is =NULL; Bytearrayoutputstream bout=NULL;Try{UriBuilder UriBuilder=NewUriBuilder (Envto.getsocketapiurl ()); HttpPost HttpPost=NewHttpPost (Uribuilder.build ()); //Httppost.setheader ("Accept", "Application/json");//after testing, this parameter is optionalHttppost.setheader ("Content-type", "Application/json");//This parameter must be setHttpClient HttpClient =httpclientbuilder.create (). build (); Jsonobject JSON=NewJsonobject (); Json.put ("Channel", channel); Json.put ("Action", action); Json.put ("Data", dataparm==NULL?Newjsonobject ():d ataparm); stringentity s=Newstringentity (json.tostring (), HTTP. UTF_8); //s.setcontentencoding (New Basicheader (HTTP. Content_Type, "Application/json"));//after testing, this parameter is optionalhttppost.setentity (s); HttpResponse HttpResponse=Httpclient.execute (HttpPost); is=httpresponse.getentity (). getcontent (); byte[] data =New byte[1024]; intLength = 0; Bout=NewBytearrayoutputstream (); while(Length=is.read (data))!=-1) {bout.write (data,0, length); The String result=NewString (Bout.tobytearray (), "UTF-8"); Logger.info ("Sendnotice2socketserver (): result is" +result);} Catch(URISyntaxException E1) {Logger.error ("Getallmembers4lucky (): IOException E1", E1);} Catch(unsupportedoperationexception e) {logger.error ("Getallmembers4lucky (): Unsupportedoperationexception E", E);} Catch(IOException e) {logger.error ("Getallmembers4lucky (): IOException E", E);} finally{ if(bout!=NULL) {ioutils.closequietly (bout); } if(is!=NULL) {ioutils.closequietly (IS); }}

Backstage can use SPRINGMVC to do a restful API (self-Bing search how to build a restful API. PS: Recommend an unusually simple frame: Spark)

---------------------------------------------------------------

Also found that more than one code could not be correctly submitted to the node. JS Service (has been 404-bad request, do not know where the problem, solve)

Then found another way to submit:

 Public StaticString postjson2socket (string url, String jsonstring,BooleanIsget,BooleanIsjson) {HttpURLConnection conn=NULL; OutputStream OS=NULL; InputStream is=NULL; BufferedReader BR=NULL; Try{        if(isget) {if(jsonstring = =NULL) {Conn= (httpurlconnection)Newurl (url). OpenConnection (); } Else{conn= (httpurlconnection)NewURL (url + "?" +jsonstring). OpenConnection (); } conn.setdooutput (false); Conn.setconnecttimeout (20000); Conn.setreadtimeout (20000); //conn.setusecaches (true);Conn.setrequestproperty ("Accept", "application/json,text/html"); Conn.setrequestproperty ("Content-type", "Application/json"); } Else{conn= (httpurlconnection)Newurl (url). OpenConnection (); Conn.setdooutput (true); Conn.setreadtimeout (10000); Conn.setrequestmethod ("POST"); Conn.setrequestproperty ("Content-type", Isjson? "Application/json": "application/x-www-form-urlencoded"); OS=Conn.getoutputstream (); Os.write (Jsonstring.getbytes ("UTF-8"));        Os.flush (); } is=Conn.getinputstream (); BR=NewBufferedReader (NewInputStreamReader (IS, "UTF-8")); StringBuffer SB=NewStringBuffer ();        String Line;  while(line = Br.readline ())! =NULL) {sb.append (line). Append ("\ n");        } br.close ();        Is.close ();        Conn.disconnect (); returnsb.tostring (); }    Catch(Exception e) {logger.error (e); return""; }    finally{ioutils.closequietly (OS);        ioutils.closequietly (BR);        Ioutils.closequietly (IS); if(conn!=NULL) {conn.disconnect (); }    }}

This method can be successfully submitted to Nodejs.

Use Apache HttpClient to Post JSON data

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.