Java emulates get and post requests for simple HTTP

Source: Internet
Author: User

background

I do Java Web Background development, often need and front-end classmate interaction, because the front background work efficiency, there will always be a time lag, before the total silly wait or poll: "Hello, the front-end written well, interactive a bit." I've been told by my brother that Firefox has a plugin that comes with a mock HTTP request, but, as a program ape, you want to write a tool class yourself by code. So, there is the httphelper.

Design

The get and post protocols are two of the most common ways of web development, where the data is not transmitted: Get requests are stitched together in the URL address, and the POST request places the data in the request body. So in the tool class to define two methods corresponding to handle two kinds of requests, and then two methods the same place (request header settings, data parsing) extracted, code reuse. I do the Web project before and after the interactive data are in JSON format, so the data stored in the map.

Code
 Packageutil;ImportJava.io.*;Importjava.net.HttpURLConnection;Importjava.net.MalformedURLException;ImportJava.net.URL;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set;/*** Simulating Http Request * Created by Michael Wong on 2016/2/24.*/ Public classHttphelper {Private Static FinalString Get_method = "GET"; Private Static FinalString Post_method = "POST"; PrivateHttphelper () {}/*** Get Request *@paramURL *@paramparameters *@returnResponsebody*/     Public StaticString get (string URL, map<string, object>parameters) {URL= URL + "?" +parseparameters (parameters); HttpURLConnection Connection=NULL; Try{URL Httpurl=Newurl (URL); Connection=(HttpURLConnection) httpurl.openconnection ();            Connection.setrequestmethod (Get_method);            Setrequestproperty (connection);            Connection.connect (); returnReceiveresponse (connection); } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally {            if(Connection! =NULL) {connection.disconnect (); }        }        return NULL; }    /*** Post Request *@paramURL *@paramparameters *@returnResponsebody*/     Public StaticString post (string URL, map<string, object>parameters) {HttpURLConnection Connection=NULL; BufferedWriter writer=NULL; Try{URL Httpurl=Newurl (URL); Connection=(HttpURLConnection) httpurl.openconnection ();            Connection.setrequestmethod (Post_method);            Setrequestproperty (connection); Writer=NewBufferedWriter (NewOutputStreamWriter (Connection.getoutputstream ()));            Writer.write (parseparameters (parameters));            Writer.flush (); returnReceiveresponse (connection); } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally {            Try {                if(Writer! =NULL) {writer.close (); }            } Catch(IOException e) {e.printstacktrace (); }            if(Connection! =NULL) {connection.disconnect (); }        }        return NULL; }    /*** Set Request Properties *@paramConnection Httpconnection*/    Private Static voidSetrequestproperty (httpurlconnection connection) {Connection.setrequestproperty ("Accept", "Application/json, Text/javascript, */*; q=0.01 "); Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded; Charset=utf-8 "); Connection.setrequestproperty ("Accept-language", "zh-cn,zh;q=0.8,en;q=0.6"); Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent", "mozilla/5.0" + "(Windows NT 6.1; WOW64) applewebkit/537.36 "+" (khtml, like Gecko) chrome/47.0.2526.111 safari/537.36 "); if(Post_method.equals (Connection.getrequestmethod ())) {Connection.setdooutput (true); } connection.setdoinput (true); }    /*** Parse Parameters *@paramparameters *@returnparsed Parameters*/    Private StaticString parseparameters (map<string, object>parameters) {        if(Parameters = =NULL) {            return""; } StringBuilder result=NewStringBuilder (); Set<map.entry<string, object>> set =Parameters.entryset (); Iterator<map.entry<string, object>> iterator =Set.iterator ();  while(Iterator.hasnext ()) {Map.entry<string, object> entry =Iterator.next (); Result.append (Entry.getkey ()). Append ("="). Append (Entry.getvalue ()). Append ("&"); }        returnResult.substring (0, Result.lastindexof ("&")); }    /*** Read Input stream *@paramConnection Http Connection *@returnResponse Body *@throwsIOException*/    Private StaticString receiveresponse (httpurlconnection connection)throwsIOException {BufferedReader reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "UTF-8")); StringBuilder receivedcontent=NewStringBuilder (1024); String Line= "";  while(line = Reader.readline ())! =NULL) {receivedcontent.append (line);        } reader.close (); returnreceivedcontent.tostring (); }}
Test
 Public class httpsimulation {    @Test    publicvoid  testsigninfromcubemaster () {         int userId = 5;         = "Http://localhost:8080/cube/user/signInFromCubeMaster";        Map<string, object> params = mapfactory.newhashmap ();        Params.put ("userid", userid);        Httphelper.get (URL, params);}    }
Concluding remarks

  Beta version, simple request to use no problem, inevitably there is a bug, welcome to the road master criticism, code has been uploaded to GitHub, welcome to hit the stars.

Java emulates get and post requests for simple HTTP

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.