Java impersonation HTTP request remote Invoke interface tool class

Source: Internet
Author: User

Package Ln;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstreamreader;import Java.io.printwriter;import Java.util.hashmap;import Java.util.list;import Java.util.Map;/** * Get/post mode used to simulate HTTP requests * @author Landa **/PublicClasshttputils {/** * Send GET request * * @param URL * Destination Address * @param parameters * Request parameter, map type. * @return Remote Response results*/Publicstatic string Sendget (string url, map<string, string>Parameters) {String result=""; BufferedReaderin =Null//Read response input stream StringBuffer SB =New StringBuffer ();//Storage Parameters Stringparams ="";//The parameters after encodingTry{//Encoding Request parametersif (parameters.size () = =1){For(String Name:parameters.keySet ()) {sb.append (name). Append ("="). Append (Java.net.URLEncoder.encode (parameters.Get(name),"UTF-8")); }params=Sb.tostring (); }Else{For(String Name:parameters.keySet ()) {sb.append (name). Append ("="). Append (Java.net.URLEncoder.encode (parameters.Get(name),"UTF-8")). Append ("&"); } String Temp_params =Sb.tostring ();params = temp_params.substring (0, Temp_params.length ()-1); } String full_url = URL +"?" +Params; System.Out. println (Full_url);//Create a URL object Java.net.URL Connurl =NewJava.net.URL (Full_url);//Open URL connection java.net.HttpURLConnection httpconn =(java.net.HttpURLConnection) Connurl. OpenConnection ();//Sets the common Properties Httpconn.setrequestproperty ("Accept","*/*"); Httpconn.setrequestproperty ("Connection","Keep-alive"); Httpconn.setrequestproperty ("User-agent","mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");//Establish an actual connectionHttpconn.connect ();//Response header gets map<string, list<string>> headers =Httpconn.getheaderfields ();//Iterate through all the response header fieldsFor(String Key:headers.keySet ()) {System.OUT.PRINTLN (key +"\t:\t"+ headers.Get(key)); }//Define the BufferedReader input stream to read the response of the URL and set the encoding methodin =New BufferedReader (NewInputStreamReader (Httpconn. getInputStream (),"UTF-8")); String Line;//Read the returned contentwhile (line =In.readline ())! =Null) {result + =Line } }Catch(Exception e) {E.printstacktrace ();}Finally{Try{if (In! =Null) {Inch. Close (); } }Catch(IOException ex) {Ex.printstacktrace ();} }Returnresult; }/** * Send POST request * * @param URL * Destination Address * @param parameters * Request parameter, map type. * @return Remote Response results*/Publicstatic string Sendpost (string url, map<string, string>Parameters) {String result ="";//Returns the result BufferedReaderin =Null//Read response input stream PrintWriterout =Null; StringBuffer SB =New StringBuffer ();//Processing Request Parameters Stringparams ="";//The parameters after encodingTry{//Encoding Request parametersif (parameters.size () = =1) {For(String Name:parameters.keySet ()) {sb.append (name). Append ("="). Append (Java.net.URLEncoder.encode (parameters.Get(name),"UTF-8")); }params = sb.tostring (); } else {for (String Name:parameters.keySet ()) {sb.append (name). Append ("="). Append (Java.net.URLEncoder.encode ( Parameters.get (name), "UTF-8")). Append ("&"); } String Temp_params = Sb.tostring (); params = temp_params.substring (0, Temp_params.length ()-1); }//Create URL object Java.net.URL connurl = new Java.net.URL (URL); Open URL connection java.net.HttpURLConnection httpconn = (java.net.HttpURLConnection) connurl. OpenConnection (); Set Common Properties Httpconn.setrequestproperty ("Accept", "*/*"); Httpconn.setrequestproperty ("Connection", "keep-alive"); Httpconn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 8.0; Windows NT 6.1) "); Set Post mode Httpconn.setdoinput (TRUE); Httpconn.setdooutput (TRUE); Gets the output stream corresponding to the HttpURLConnection object out = new PrintWriter (Httpconn.getoutputstream ()); Send request parameter out.write (params); Flush output Stream Buffer Out.flush (); Define the BufferedReader input stream to read the response of the URL, set the encoding in = new BufferedReader (New InputStreamReader (Httpconn. getInputStream (), " UTF-8 ")); String LinE Reads the returned content while (line = In.readline ()) = null) {result + = line;}} catch (Exception e) {e.printstacktrace ();} finally {try {if (out! = null) {Out.close ();} if (in! = null) {In.close ( ); }} catch (IOException ex) {ex.printstacktrace ();}} return result; }/** * Main function, test request * * @param args */public static void main (string[] args) {map<string, string> parameters = new Ha Shmap<string, string> (); Parameters.put ("name", "Sarin"); String result =sendget ("http://www.baidu.com", parameters); SYSTEM.OUT.PRINTLN (result); } }

Java impersonation HTTP request remote Invoke interface tool class

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.