Java implementation of HTTP request (GET, POST) method

Source: Internet
Author: User

When using Java to make a service call, avoid the use of simulated HTTP requests to implement the simulation, I happen to encounter this kind of business requirements in the development process, so on this kind of method is a summary, the principle level of things temporarily do not consider, after all, the bottom of the HTTP implementation of what, things are quite complex, For my project, understand these things can not be clearly from the intuitive to improve or help, or the code to compare the actual, so, put a summary of several methods, as a backup, free of the future and then re-build the wheel.

The first: The Idiot program, the most original solution, the function is implemented temporarily, but it will involve the universality and performance issues, temporarily do not consider, the code is as follows

 Public classHttpRequest {Private Static FinalLogger Logger = Loggerfactory.getlogger (HttpRequest.class. GetName ()); /*** A request to send a GET method to a specified URL *@paramURL to send the request to *@paramparam The request parameter, the request parameter should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented by the URL*/     Public Staticstring sendget (string url, string param) {StringBuilder result=NewStringBuilder (); BufferedReader BufferedReader=NULL; Try{String urlnamestring= URL + "?" +param; URL Realurl=NewURL (urlnamestring); //opening and linking between URLsURLConnection connection =realurl.openconnection (); //to set common request propertiesConnection.setrequestproperty ("Accept", "*/*"); Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent", "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); //establish an actual connectionConnection.connect (); //Get all response header fieldsmap<string, list<string>> map =Connection.getheaderfields (); //iterate through all the response header fields             for(String key:map.keySet ()) {Logger.info ("Key: {}", Map.get (key)); SYSTEM.OUT.PRINTLN (Key+ "--->" +Map.get (key)); }            //defines the response of the BufferedReader input stream to read the URLBufferedReader =NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));            String Line;  while(line = Bufferedreader.readline ())! =NULL) {result.append (line); }        } Catch(Exception e) {logger.error ("HTTP GET error: {}", E.getmessage ()); }        //Use the finally block to close the input stream        finally {            Try {                if(BufferedReader! =NULL) {bufferedreader.close (); }            } Catch(Exception E2) {e2.printstacktrace (); }        }        returnresult.tostring (); }    /*** Request to send the Post method to the specified URL * *@paramURL to send the request to *@paramparam The request parameter, the request parameter should be in the form of name1=value1&name2=value2. * @returnThe response result of the remote resource represented*/     Public Staticstring sendpost (string url, string param) {logger.info ("URL: {}", URL); Logger.info ("Param: {}", param); PrintWriter out=NULL; BufferedReader in=NULL; StringBuilder result=NewStringBuilder (); Try{URL Realurl=Newurl (URL); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); Conn.setrequestproperty ("Accept-language", "en-us,en;q=0.5"); //To send a POST request, you must set the following two linesConn.setdooutput (true); Conn.setdoinput (true); //gets the output stream corresponding to the URLConnection objectout =NewPrintWriter (Conn.getoutputstream ()); //Send Request Parametersout.print (param); //buffer for flush output streamOut.flush (); //defines the response of the BufferedReader input stream to read the URLin =NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));            String Line;  while(line = In.readline ())! =NULL) {result.append (line); }        } Catch(Exception e) {logger.error ("HTTP POST error: {}", E.getmessage ()); }        //Use the finally block to close the output stream, input stream        finally {            Try {                if(Out! =NULL) Out.close (); if(In! =NULL) In.close (); } Catch(IOException ex) {Logger.error ("Close IO error: {}", Ex.getmessage ()); }        }        returnresult.tostring (); }}

The second: The upgraded version, based on the previous version of the simplified version, looks more concise, the code is as follows

 Public classHttpclientutil {Private Static FinalLogger Logger = Loggerfactory.getlogger (httpclientutil.class. GetName ());  Public StaticString sendget (string url, string param)throwsIOException {logger.info ("Request URL info: {}", URL); HttpGet Request=NewHttpGet (URL + "?" +param); returnSend (Request); }     Public StaticString sendpost (string url, string param)throwsIOException {logger.info ("Request URL info: {}", URL); HttpPost Request=Newhttppost (URL); Request.setentity (NewStringentity (param, contenttype.create ("Application/json;charset=utf-8"))        ); returnSend (Request); }    Private StaticString Send (Httprequestbase request)throwsIOException {String message= ""; Request.setheader ("User-agent", "mozilla/5.0 (Windows NT 6.1; WOW64) ... "); Request.setheader ("Accept", "*/*"); Request.setheader ("Connection", "keep-alive"); Closeablehttpclient httpclient=Httpclients.createdefault (); Closeablehttpresponse Response=Httpclient.execute (Request); Httpentity Entity=response.getentity (); Bytearrayoutputstream OutStream=NewBytearrayoutputstream (); if(Entity! =NULL) {            LongLength =entity.getcontentlength (); if(Length! =-1 && Length < 2048) {Message=entityutils.tostring (entity); } Else{InputStream in=entity.getcontent (); byte[] data =New byte[4096]; intcount;  while((count = in.read (data, 0, 4096))! =-1) {outstream.write (data,0, Count); } Message=NewString (Outstream.tobytearray (), "UTF-8"); }} logger.info (">>>>>>>>>>>>>>>>>response message info: {}", message); returnmessage; }}

The third: This kind of program, completely farewell to the Fool-type wheel creation process, directly using open source, packaged code tools to achieve this process, but there is a problem is that he will produce a polling log, so as to keep the link communication, if you look uncomfortable, you can change the source configuration, Or use the log filter in the LOG4J2, directly filter out his log, and only print the program's log information, it looks more refreshing, the code is as follows (PS: This toolkit to support the full range of Resful request, here only the two commonly used, the others please do their own experiment)

 Public classUnirestutil {Private Static FinalLogger Logger = Loggerfactory.getlogger (unirestutil.class. GetName ()); /**     *     * @paramURL Destination URL *@paramName parameter names *@paramparam Request Parameters *@returnNetwork transfer Status Code or request result*/     Public StaticHttpResponse sendget (string url, string name, string param)throwsunirestexception {logger.debug ("Request URL info: {}", URL); HttpResponse<String> response =unirest.get (URL). Header ("Accept", "Application/json;charset=utf-8"). queryString (name, param). asstring (); Logger.debug ("Response status info: {}", Response.getstatus ()); Logger.debug ("Response Status Message info: {}", Response.getstatustext ()); returnresponse; }    /**     *     * @paramURL Destination URL *@paramName parameter names *@paramparam request Parameter entity *@returnNetwork transfer Status Code*/     Public StaticHttpResponse sendpost (string url, string name, string param)throwsunirestexception {logger.debug ("Request URL info: {}", URL); HttpResponse<String> response =unirest.post (URL). Header ("Accept", "Application/json;charset=utf-8"). queryString (name, param). asstring (); Logger.debug ("Response status info: {}", Response.getstatus ()); Logger.debug ("Response Status Message info: {}", Response.getstatustext ()); returnresponse; }}

OK, at this point, several programs are posted out, there may be more concise and reliable solution to achieve this function, but I have not found, if you have a better way, please message exchange, share it, thank you.

Java implementation of HTTP request (GET, POST) method

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.