Java send HTTP request, return HTTP response content, instance and application

Source: Internet
Author: User
Tags http request 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:


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 * parameter set * @return Response object * @throws IOException */Public httprespons sendget (String urlstring, map<string, string> params) throws IO Exception {return this.send (urlstring, "get", params, NULL); /** * Send GET request * * @param urlstring * URL address * @param params * parameter set * @param prope Rtys * Request Attribute * @return Response object * @throws IOException/public httprespons sendget (String urlstring, MAP&L T 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 * parameter set * @return response Like * @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 * parameter set * @param propertys * Request Attribute * @return Response Object * @thro WS IOException */public httprespons sendpost (String urlstring, map<string, string> params, map<string, Str
	Ing> propertys) throws IOException {return this.send (urlstring, "POST", params, propertys); /** * Send HTTP request * * @param urlstring * @return The object * @throws IOException/private httprespons Send (St Ring URLString, String method, map<string, string> parameters, map<string, string> propertys) throws IOE
 
		xception {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); /** * Received Response object * * @param urlconnection * @return Response Object * @throws IOException/private Httprespons MAKEC
			Ontent (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.defaultcontent
	Encoding = 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:


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

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.csdn.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.