Java sends an HTTP POST request

Source: Internet
Author: User

Package Com.sm.utils;import Java.io.bufferedreader;import java.io.inputstreamreader;import java.io.PrintWriter ; Import Java.net.url;import Java.net.urlconnection;import java.util.arraylist;import Java.util.hashmap;import Java.util.list;import Java.util.map;import Org.springframework.web.multipart.multiparthttpservletrequest;import Org.apache.http.namevaluepair;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.closeablehttpresponse;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;import Org.apache.http.message.basicnamevaluepair;import org.apache.http.util.EntityUtils; Public classHttputils { Public StaticFinal String CHARSET ="UTF-8"; //send GET request url?a=x&b=xx form     Public Staticstring sendget (string url, string param) {string result=""; BufferedReaderinch=NULL; Try{String urlname=""; if(Param.length ()! =0) {urlname= URL +"?"+param; } ElseURLName=URL; URL Resurl=NewURL (urlname); URLConnection Urlconnec=resurl.openconnection (); Urlconnec.setrequestproperty ("Accept","*/*"); Urlconnec.setrequestproperty ("Connection","keep-alive"); Urlconnec.setrequestproperty ("user-agent","mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");            Urlconnec.connect (); Map<string, list<string>> map =Urlconnec.getheaderfields ();  for(String key:map.keySet ()) {System. out. println (Key +"--->"+ map.Get(key)); }            //defines the response of the BufferedReader input stream to read the URL            inch=NewBufferedReader (NewInputStreamReader (Urlconnec.getinputstream ()));            String Line;  while(line =inch. ReadLine ())! =NULL) {result+=Line ; }        } Catch(Exception e) {System. out. println ("failed to send GET request"+e);        E.printstacktrace (); } finally {            Try {                if(inch!=NULL) {                    inch. Close (); }            } Catch(Exception e) {e.printstacktrace (); }        }        returnresult; }    //send a POST request     Public Staticstring sendpost (string url, multiparthttpservletrequest param) {string result=""; PrintWriter out=NULL; BufferedReaderinch=NULL; Try{URL Resurl=Newurl (URL); URLConnection Urlconnec=resurl.openconnection (); Urlconnec.setrequestproperty ("Accept","*/*"); Urlconnec.setrequestproperty ("Connection","keep-alive"); Urlconnec.setrequestproperty ("user-agent","mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //to send a POST request, you must set the following two linesUrlconnec.setdoinput (true); Urlconnec.setdooutput (true);  out=NewPrintWriter (Urlconnec.getoutputstream ());  out. print (param);//Send Post Parameters             out. Flush (); //defines the response of the BufferedReader input stream to read the URL            inch=NewBufferedReader (NewInputStreamReader (Urlconnec.getinputstream ()));            String Line;  while(line =inch. ReadLine ())! =NULL) {result+=Line ; }        } Catch(Exception e) {System. out. println ("POST request send failed"+e);        E.printstacktrace (); } finally {            Try {                if(inch!=NULL) {                    inch. Close (); }                if( out!=NULL) {                     out. Close (); }            } Catch(Exception e) {e.printstacktrace (); }        }        returnresult; }            //Post Request Method     Public StaticString sendpost (string URL, map<string,object>params) {String response=NULL; System. out. println (URL); System. out. println (params); Try{List<NameValuePair> pairs =NULL; if(params!=NULL&&!params. IsEmpty ()) {Pairs=NewArraylist<namevaluepair> (params. Size ());  for(String key:params. KeySet ()) {Pairs.add (NewBasicnamevaluepair (Key,params.Get(Key). ToString ())); }} closeablehttpclient httpclient=NULL; Closeablehttpresponse HttpResponse=NULL; Try{httpclient=Httpclients.createdefault (); HttpPost HttpPost=Newhttppost (URL); //stringentity stringentity = new stringentity (data);               if(Pairs! =NULL&& pairs.size () >0) {httppost.setentity (Newurlencodedformentity (pairs, CHARSET)); } HttpResponse=Httpclient.execute (HttpPost); Response=entityutils. ToString (Httpresponse.getentity ()); System. out. println (response); } finally {               if(HttpClient! =NULL) {httpclient.close (); }               if(HttpResponse! =NULL) {httpresponse.close (); }           }       } Catch(Exception e) {e.printstacktrace (); }       returnresponse; }     Public Static voidMain (string[] args) {Map<String,Object> map =NewHashmap<string,object>(); Map.put ("ID","123456666"); Sendpost ("Http://192.168.1.56:8080/smkj/api/lcds/user/lcdsUser", map); }    /** * Test * Description: Here with Sina stock interface do get test, Sina stock interface does not support JSONP, as for post, because I use the company's interface does not show, the same, a URL, a packet*/    /** public static void Main (string[] args) {//TODO auto-generated method * stub String Resultget = Sendget (" /c1>http://hq.sinajs.cn/list=sh600389",""); * SYSTEM.OUT.PRINTLN (Resultget); }     */}

Java sends an HTTP POST request

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.