Post and get requests in Java

Source: Internet
Author: User

Example code:

 PackageCom.shareboxes.util;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importjava.net.URLConnection;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportOrg.junit.Ignore;Importorg.junit.Test;/*** @ClassName: httprequest* @Description: Get,post Request *@authoradministrator* @date October 19, 2015 **/ Public classHttpRequest {/*** @Title: Sendget * @Description: GET request *@paramURL *@paramparam*/     Public StaticString sendget (string url, map<string, string>param) {BufferedReader Breader=NULL; StringBuffer Sbuffer=NewStringBuffer (); String Realurl=URL; Try {                        if(Param.size () > 0) {Realurl+= "?";  for(Entry<string, string>Entry:param.entrySet ()) {Realurl+ = Entry.getkey () + "=" + entry.getvalue () + "&"; } Realurl= realurl.substring (0, Realurl.length ()-1); } URL urlstring=NewURL (Realurl); URLConnection URLConnection=urlstring.openconnection (); HttpURLConnection HttpURLConnection=(httpurlconnection) URLConnection; Httpurlconnection.setrequestmethod ("GET");//Set Request MethodHttpurlconnection.setconnecttimeout (30000);//Connection host timeout timeHttpurlconnection.setreadtimeout (30000);//Read Data timeout timeHttpurlconnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");//format the request dataHttpurlconnection.setrequestproperty ("Connection", "keep-alive"); Httpurlconnection.setrequestproperty ("Accept-charset", "utf-8");//set the encoding of the received data//determine if the connection is abnormal            if(Httpurlconnection.getresponsecode () >= 300) {                Throw NewException ("HTTP Request isn't success, Response code is" +Httpurlconnection.getresponsecode ());            } System.out.println (Httpurlconnection.getresponsecode ());  for(Entry<string, list<string>>entry:httpURLConnection.getHeaderFields (). EntrySet ()) {System.out.println (Entry.getkey ()+ "--------->" +Entry.getvalue ()); } Breader=NewBufferedReader (NewInputStreamReader (Urlconnection.getinputstream (), "Utf-8")); String Line=NULL;  while(line = Breader.readline ())! =NULL) {sbuffer.append (line); }        } Catch(Exception e) {System.out.println ("GET request has an error!!!");        E.printstacktrace (); } finally {            if(Breader! =NULL) {                Try{breader.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }        returnsbuffer.tostring (); }    /*** @Title: Sendpost * @Description: POST request *@paramURL *@paramparam*/     Public StaticString sendpost (string url, map<string, string>param) {BufferedReader Breader=NULL; OutputStreamWriter out=NULL; StringBuffer Sbuffer=NewStringBuffer (); String Parameterdata=""; Try {            if(Param.size () > 0) {                 for(Entry<string, string>Entry:param.entrySet ()) {Parameterdata+ = Entry.getkey () + "=" + entry.getvalue () + "&"; } parameterdata= parameterdata.substring (0, Parameterdata.length ()-1); } URL Realurl=Newurl (URL); HttpURLConnection HttpURLConnection=(HttpURLConnection) realurl.openconnection (); Httpurlconnection.setconnecttimeout (30000); Httpurlconnection.setreadtimeout (30000); Httpurlconnection.setrequestmethod ("POST"); Httpurlconnection.setdooutput (true); Httpurlconnection.setdoinput (true); Httpurlconnection.setusecaches (false); Httpurlconnection.setinstancefollowredirects (true); Httpurlconnection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");//format the request parametersHttpurlconnection.setrequestproperty ("Connection", "keep-alive"); Httpurlconnection.setrequestproperty ("Accept-charset", "utf-8");//encoding of received data                        if((Parameterdata.trim (). Length () >0) && (!parameterdata.equals ("")) { out=NewOutputStreamWriter (Httpurlconnection.getoutputstream (), "Utf-8");                Out.write (Parameterdata);            Out.flush (); }                        //determine if the connection is abnormal            if(Httpurlconnection.getresponsecode () >= 300) {                Throw NewException ("HTTP Request isn't success, Response code is" +Httpurlconnection.getresponsecode ());            } System.out.println (Httpurlconnection.getresponsecode ());  for(Entry<string, list<string>>entry:httpURLConnection.getHeaderFields (). EntrySet ()) {System.out.println (Entry.getkey ()+ "--------->" +Entry.getvalue ()); }            //Breader = new BufferedReader (New InputStreamReader (Httpurlconnection.getinputstream (), "Utf-8"));//String line = null;//While (line = Breader.readline ()) = null) {//Sbuffer.append (line);//            }InputStream in=Httpurlconnection.getinputstream (); byte[]data=New byte[Httpurlconnection.getcontentlength ()]; intOffset=0;  while(offset<in.available ()) {Offset+=in.read (data, offset, in.available ()-offset);            System.out.println (offset); } sbuffer.append (NewString (data, "Utf-8")); } Catch(Exception e) {System.out.println ("POST request failed!!! ");        E.printstacktrace (); } finally {            Try {                if(Out! =NULL) {out.close (); }                if(Breader! =NULL) {breader.close (); }            } Catch(Exception E2) {e2.printstacktrace (); }        }        returnsbuffer.tostring (); } @Test @Ignore Public voidTestget () {Map<string, string> param =NewHashmap<string, string>(); Param.put ("Tid", "1"); System.out.println (Sendget ("Http://localhost:8080/shareboxes/record/getrecord/tid.do", param)); } @Test Public voidTestpost () {Map<string, string> param =NewHashmap<string, string>(); Param.put ("Tid", "1"); System.out.println (Sendpost ("Http://localhost:8080/shareboxes/record/getrecord/tid.do", param)); }}

Post and get requests in Java

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.