Java sends HTTP request, returns HTTP response content, application and instance code _java

Source: Internet
Author: User
Tags readline stringbuffer

There are some support for stateless protocol requests (HTTP) in the JDK, and I'll describe a small example (component) I wrote:
Let's first build a request Class (Httprequester).
This class encapsulates the JAVA implementation code for a simple request, as follows:

Copy Code code as follows:



Import Java.io.BufferedReader;


Import java.io.IOException;


Import Java.io.InputStream;


Import Java.io.InputStreamReader;


Import java.net.HttpURLConnection;


Import Java.net.URL;


Import Java.nio.charset.Charset;


Import Java.util.Map;


Import Java.util.Vector;





/**


* HTTP Request Object


*


* @author Yymmiinngg


*/


public class Httprequester {


Private String defaultcontentencoding;





Public Httprequester () {


this.defaultcontentencoding = Charset.defaultcharset (). Name ();


}





/**


* Send GET request


*


* @param urlstring


* URL Address


* @return Response Object


* @throws IOException


*/


Public httprespons Sendget (String urlstring) throws IOException {


Return This.send (urlstring, ' get ', NULL, NULL);


}





/**


* Send GET request


*


* @param urlstring


* URL Address


* @param params


* Parameters Collection


* @return Response Object


* @throws IOException


*/


Public httprespons Sendget (String urlstring, map<string, string> params)


Throws IOException {


Return This.send (urlstring, "get", params, null);


}





/**


* Send GET request


*


* @param urlstring


* URL Address


* @param params


* Parameters Collection


* @param propertys


* Request Properties


* @return Response Object


* @throws IOException


*/


Public httprespons Sendget (String urlstring, map<string, string> params,


Map<string, string> propertys) throws IOException {


Return This.send (urlstring, "get", params, propertys);


}





/**


* Send POST request


*


* @param urlstring


* URL Address


* @return Response Object


* @throws IOException


*/


Public httprespons sendpost (String urlstring) throws IOException {


Return This.send (urlstring, "POST", NULL, NULL);


}





/**


* Send POST request


*


* @param urlstring


* URL Address


* @param params


* Parameters Collection


* @return Response Object


* @throws IOException


*/


Public httprespons sendpost (String urlstring, map<string, string> params)


Throws IOException {


Return This.send (urlstring, "POST", params, null);


}





/**


* Send POST request


*


* @param urlstring


* URL Address


* @param params


* Parameters Collection


* @param propertys


* Request Properties


* @return Response Object


* @throws IOException


*/


Public httprespons sendpost (String urlstring, map<string, string> params,


Map<string, string> propertys) throws IOException {


Return This.send (urlstring, "POST", params, propertys);


}





/**


* Send HTTP request


*


* @param urlstring


* @return The object to be reflected


* @throws IOException


*/


Private httprespons Send (String urlstring, String method,


map<string, string> parameters, map<string, string> propertys)


Throws IOException {


HttpURLConnection urlconnection = null;





if (Method.equalsignorecase ("get") && parameters!= null) {


StringBuffer param = new StringBuffer ();


int i = 0;


For (String Key:parameters.keySet ()) {


if (i = = 0)


Param.append ("?");


Else


Param.append ("&");


Param.append (Key). Append ("="). Append (Parameters.get (key));


i++;


}


URLString + = param;


}


URL url = new URL (urlstring);


URLConnection = (httpurlconnection) url.openconnection ();





Urlconnection.setrequestmethod (method);


Urlconnection.setdooutput (TRUE);


Urlconnection.setdoinput (TRUE);


Urlconnection.setusecaches (FALSE);





if (propertys!= null)


For (String Key:propertys.keySet ()) {


Urlconnection.addrequestproperty (Key, Propertys.get (key));


}





if (Method.equalsignorecase ("POST") && parameters!= null) {


StringBuffer param = new StringBuffer ();


For (String Key:parameters.keySet ()) {


Param.append ("&");


Param.append (Key). Append ("="). Append (Parameters.get (key));


}


Urlconnection.getoutputstream (). Write (Param.tostring (). GetBytes ());


Urlconnection.getoutputstream (). Flush ();


Urlconnection.getoutputstream (). Close ();


}





Return This.makecontent (urlstring, URLConnection);


}





/**


* Get the Response object


*


* @param urlconnection


* @return Response Object


* @throws IOException


*/


Private Httprespons makecontent (String urlstring,


HttpURLConnection urlconnection) throws IOException {


Httprespons httpresponser = new Httprespons ();


try {


InputStream in = Urlconnection.getinputstream ();


BufferedReader BufferedReader = new BufferedReader (


New InputStreamReader (in));


Httpresponser.contentcollection = new vector<string> ();


StringBuffer temp = new StringBuffer ();


String line = Bufferedreader.readline ();


while (line!= null) {


HttpResponser.contentCollection.add (line);


Temp.append (line). Append ("\ r \ n");


line = Bufferedreader.readline ();


}


Bufferedreader.close ();





String ecod = urlconnection.getcontentencoding ();


if (ecod = null)


Ecod = this.defaultcontentencoding;





httpresponser.urlstring = urlstring;





Httpresponser.defaultport = Urlconnection.geturl (). Getdefaultport ();


Httpresponser.file = Urlconnection.geturl (). GetFile ();


Httpresponser.host = Urlconnection.geturl (). GetHost ();


Httpresponser.path = Urlconnection.geturl (). GetPath ();


Httpresponser.port = Urlconnection.geturl (). Getport ();


Httpresponser.protocol = Urlconnection.geturl (). Getprotocol ();


Httpresponser.query = Urlconnection.geturl (). Getquery ();


Httpresponser.ref = Urlconnection.geturl (). GETREF ();


Httpresponser.userinfo = Urlconnection.geturl (). GetUserInfo ();





Httpresponser.content = new String (temp.tostring (). GetBytes (), ecod);


httpresponser.contentencoding = Ecod;


Httpresponser.code = Urlconnection.getresponsecode ();


Httpresponser.message = Urlconnection.getresponsemessage ();


Httpresponser.contenttype = Urlconnection.getcontenttype ();


Httpresponser.method = Urlconnection.getrequestmethod ();


Httpresponser.connecttimeout = Urlconnection.getconnecttimeout ();


Httpresponser.readtimeout = Urlconnection.getreadtimeout ();





return httpresponser;


catch (IOException e) {


Throw e;


finally {


if (urlconnection!= null)


Urlconnection.disconnect ();


}


}





/**


* Default Response Character Set


*/


Public String getdefaultcontentencoding () {


return this.defaultcontentencoding;


}





/**


* Set the default response character set


*/


public void setdefaultcontentencoding (String defaultcontentencoding) {


this.defaultcontentencoding = defaultcontentencoding;


}


}


Next, let's look at the Response object (httprespons). The response object is actually just a data bean that encapsulates the result data for the request response, as follows:

Copy Code code as follows:



Import Java.util.Vector;





/**


* Response Object


*/


public class Httprespons {





String urlstring;





int defaultport;





String file;





String host;





String path;





int port;





String Protocol;





String query;





String ref;





String UserInfo;





String contentencoding;





String content;





String ContentType;





int code;





String message;





String method;





int connecttimeout;





int readtimeout;





Vector<string> contentcollection;





Public String getcontent () {


return content;


}





Public String getContentType () {


return contentType;


}





public int GetCode () {


return code;


}





Public String GetMessage () {


return message;


}





Public vector<string> getcontentcollection () {


return contentcollection;


}





Public String getcontentencoding () {


return contentencoding;


}





Public String GetMethod () {


return method;


}





public int getconnecttimeout () {


return connecttimeout;


}





public int getreadtimeout () {


return readtimeout;


}





Public String geturlstring () {


return urlstring;


}





public int Getdefaultport () {


return defaultport;


}





Public String GetFile () {


return file;


}





Public String GetHost () {


return host;


}





Public String GetPath () {


return path;


}





public int Getport () {


return port;


}





Public String Getprotocol () {


return protocol;


}





Public String Getquery () {


return query;


}





Public String GetRef () {


return ref;


}





Public String GetUserInfo () {


return userInfo;


}





}


Finally, let's write an application class that tests whether the above code is correct

Copy Code code as follows:



Import Com.yao.http.HttpRequester;


Import com.yao.http.HttpRespons;





public class Test {


public static void Main (string[] args) {


try {


Httprequester request = new Httprequester ();


Httprespons hr = Request.sendget ("http://www.jb51.net");





System.out.println (Hr.geturlstring ());


System.out.println (Hr.getprotocol ());


System.out.println (Hr.gethost ());


System.out.println (Hr.getport ());


System.out.println (Hr.getcontentencoding ());


System.out.println (Hr.getmethod ());





System.out.println (Hr.getcontent ());





catch (Exception e) {


E.printstacktrace ();


}


}


}


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.