Tidy up the method of simulating HTTP requests with Java, if there is an incorrect place to ask you to correct, if you have any better way to welcome the proposed
1, URLConnection can send a request to the URL address, read the URL resources. Establishing a connection to a URL usually takes a few steps:
- Create the URL object and obtain the URLConnection object by calling the OpenConnection method;
- Set URLConnection parameters and normal request properties;
- Send a request to a remote resource;
- When a remote resource becomes available, the program can access the remote resource's header field and read the information returned by the remote resource through the input stream.
Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.printwriter;import java.net.url;import java.net.urlconnection;import Java.util.list;import java.util.Map;PublicClassHttpRequest {/** * A request to send a GET method to a specified URL * * @param URL to send the requested URL * @param param request parameter, the request parameter should be in the form of name1=value1&name2=value2. * @return The response result of the remote resource represented by the URL*/PublicStaticString sendget (string url, string param) {string result =""; BufferedReaderin =Null;Try{String urlnamestring = URL +"?" +Param URL Realurl =NewURL (urlnamestring);//Connection between open and URL urlconnection connection =Realurl.openconnection ();//Sets the common request Properties Connection.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 fields Map<string, list<string>> Map =Connection.getheaderfields ();//Iterate through all the response header fieldsFor(String Key:map.keySet ()) {System.OUT.PRINTLN (key +"--->"+ map.Get(key)); }//Defines the response of the BufferedReader input stream to read the URLin =New BufferedReader (NewInputStreamReader (Connection.getinputstream ())); String Line;while (line =In.readline ())! =Null) {result + =Line } }Catch(Exception e) {System.Out.println ("Send GET request Exception!" +e); E.printstacktrace (); }//Use the finally block to close the input streamFinally{Try{if (In! =Null) {Inch. Close (); } }Catch(Exception E2) {E2.printstacktrace ();} }ReturnResult }/** * A request to send a POST method to a specified URL * * @param URL to send the requested URL * @param the param request parameter, the request parameter should be in the form of name1=value1&name2=value2. * @return The response result of the remote resource represented*/PublicStaticString sendpost (string url, string param) {PrintWriterout =Null; BufferedReaderin =Null; String result ="";Try{URL Realurl =NewURL (URL);//Connection between open and URL URLConnection conn =Realurl.openconnection ();//Sets the common request Properties Conn.setrequestproperty ("Accept","*/*"); Conn.setrequestproperty ("Connection","Keep-alive"); Conn.setrequestproperty ("User-agent","mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");//To send a POST request, you must set the following two lines Conn.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 + =Line } }Catch(Exception e) {System.out.println ( send POST Request Exception! "+e); E.printstacktrace (); } //finally{try{if (out!=nullout.close ();} if (in!=null) {in.close ();}} catch (IOException ex) {ex.printstacktrace ();}} return result; } }
Test method
PublicStaticvoidMain (string[] args) {//Send GET request String S=httprequest.sendget ("http://localhost:6144/Home/RequestString", "key=123&v=456"); System. out. println (s); // send POST request String sr=httprequest.sendpost ("http://localhost:6144/Home/RequestPostString" , "key=123&v=456"); System. out. println (SR);}
Refer to Article 1,http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html
2,http://www.cnblogs.com/ribavnu/archive/2013/05/17/3084060.html
2, HttpClient
Import java.io.IOException;
Import Java.util.Map;
Import org.apache.commons.httpclient.HttpClient;
Import org.apache.commons.httpclient.HttpException;
Import Org.apache.commons.httpclient.HttpMethod;
Import Org.apache.commons.httpclient.NameValuePair;
Import Org.apache.commons.httpclient.methods.GetMethod;
Import Org.apache.commons.httpclient.methods.PostMethod;
Import Org.apache.commons.httpclient.params.HttpMethodParams;
public class Httpclienttest {
/**
* @param URL to send the requested address
* @param params request parameter (Name=username&password=password)
* @throws Exception
*/
public void GetMethod (String url,string params) throws exception{
HttpClient client = new HttpClient ();
Setting the encoding problem
Client.getparams (). Setparameter (Httpmethodparams.http_content_charset, "utf-8");
HttpMethod method = new GetMethod (url+ "?") +params);
Add parameters sent by a GET request, such as cookies
Method.addrequestheader ("User-agent", "mozilla/5.0" (Windows NT 6.1; WOW64; rv:39.0) gecko/20100101 firefox/39.0 ");
Request to execute get
Client.executemethod (method);
Directly get the result of a plea return
String result = Method.getresponsebodyasstring ();
SYSTEM.OUT.PRINTLN (result);
}
/**
* @param URL to send the requested address
* Parameter map for @param params request
* @throws HttpException
* @throws IOException
*/
public void Postmethod (String url,map<string,string> params) throws HttpException, ioexception{
HttpClient client = new HttpClient ();
Setting the encoding problem
Client.getparams (). Setparameter (Httpmethodparams.http_content_charset, "utf-8");
Postmethod method = new Postmethod (URL);
namevaluepair[] names = new namevaluepair[params!=null? Params.size (): 0];
int i = 0;
if (params!=null) {
For (String Key:params.keySet ()) {
Names[i] = new Namevaluepair (key, Params.get (key));
i++;
}
}
Set various parameters of method
Method.addrequestheader ("User-agent", "mozilla/5.0" (Windows NT 6.1; WOW64; rv:39.0) gecko/20100101 firefox/39.0 ");
Method.addparameters (names);
Client.executemethod (method);
String result = Method.getresponsebodyasstring ();
SYSTEM.OUT.PRINTLN (result);
}
Test method
public static void Main (string[] args) throws Exception {
Httpclienttest test = new Httpclienttest ();
Test.getmethod ("https://www.baidu.com/", "" ");
}
}
Java Impersonation HTTP request