Java uses httpclient to implement post requests

Source: Internet
Author: User
Tags session id

Http://www.cnblogs.com/mengrennwpu/p/6418114.html

*******************************************

Based on the project requirements, want to implement post message push, so the implementation of the HttpClient component, the relevant code is as follows (note: The program uses the HttpClient and Httpcore dependent package version is 4.2.5):

ImportOrg.apache.http.Header;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.entity.StringEntity;Importorg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.params.CoreConnectionPNames;ImportJava.util.UUID;ImportNet.sf.json.JSONObject;ImportJava.nio.charset.Charset; Public Static BooleanHttppostwithjson (jsonobject jsonobj,string url,string appId) {BooleanIssuccess =false; HttpPost Post=NULL; Try{HttpClient HttpClient=Newdefaulthttpclient (); //setting the time-out periodHttpclient.getparams (). Setparameter (Coreconnectionpnames.connection_timeout, 2000); Httpclient.getparams (). Setparameter (Coreconnectionpnames.so_timeout,2000); Post=Newhttppost (URL); //Construct message HeadersPost.setheader ("Content-type", "Application/json; Charset=utf-8 "); Post.setheader ("Connection", "Close"); String sessionId=GetSessionID (); Post.setheader ("SessionId", sessionId); Post.setheader ("AppID", AppID); //Building Message Entitiesstringentity entity =NewStringentity (Jsonobj.tostring (), Charset.forname ("UTF-8")); Entity.setcontentencoding ("UTF-8"); //send data requests in JSON formatEntity.setcontenttype ("Application/json");                    Post.setentity (entity); HttpResponse Response=Httpclient.execute (POST); //Check return code        intStatusCode =response.getstatusline (). Getstatuscode (); if(StatusCode! =HTTPSTATUS.SC_OK) {Logutil.info ("Request Error:" +StatusCode); Issuccess=false; }Else{            intRetCode = 0; String Sessendid= ""; //The return code contains the Retcode and the session 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 PrintingLogutil.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 (); }        }    }    returnissuccess;}//build unique session ID Public StaticString GetSessionID () {uuid UUID=Uuid.randomuuid (); String Str=uuid.tostring (); returnStr.substring (0, 8) + str.substring (9, +) + str.substring (+) + str.substring (+ +) + str.substring (24);}

Ps: When sending a POST request using a Hadoop cluster, there is a "Java.lang.NoSuchFieldError:INSTANCE" problem, which is usually caused by a "jar packet conflict" problem. But the strange thing is that the local Pom.xml setting has the field in the dependency package, and the associated HttpClient dependency package is as follows:

<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 found on the Internet, to find the cause of the problem, because the Hadoop cluster running the program, the first load of its own directory of the Jar package, in its own directory if not found, will be loaded when the program runtime specified by the jar package (see:/http bbs.umeng.com/thread-12187-1-1.html), along with the associated jar package path in the Hadoop cluster, The associated dependency package for httpclient is found to be 4.2.5, so the Pom.xml configuration file is also updated to that version, and the program runs through.

Java uses httpclient to implement post requests

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.