Tool classes related to asynchronous networks Httputils

Source: Internet
Author: User
Tags finally block

Tool classes related to asynchronous networks
Package Com.flyou.utils;import Java.io.bufferedreader;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.PrintWriter;import Java.net.httpurlconnection;import java.net.url;/** * HTTP Request Tool Class * * @author flyou * */public class Httputils{private STA Tic Final int timeout_in_millions = 4000;public interface callback{void onrequestcomplete (String result); /** * Asynchronous GET Request * * @param urlstr * @param callBack */public static void Dogetasyn (Final String urlstr, final callBack cal Lback) {new Thread () {public void run () {try{string result = Doget (URLSTR); if (callBack! = null) { Callback.onrequestcomplete (result);}} catch (Exception e) {e.printstacktrace ();}};}. Start ();} /** * Asynchronous POST Request * @param urlstr * @param params * @param callBack * @throws Exception */public static void Dopostasyn (FINA L string urlstr, final string params,final CallBack CallBack) throws Exception{new Thread () {public void run () {try{string R Esult =DoPost (urlstr, params); if (callBack! = null) {Callback.onrequestcomplete (result);}} catch (Exception e) {e.printstacktrace ();}};}. Start ();}  /** * GET request, get return data * * @param urlstr * @return * @throws Exception */public static string doget (String urlstr) {URL url = Null HttpURLConnection conn = Null;inputstream is = null; Bytearrayoutputstream BAOs = null;try{url = new URL (urlstr); conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (timeout_in_millions); Conn.setconnecttimeout (timeout_in_millions); Conn.setRequestMethod (" GET "), Conn.setrequestproperty (" Accept "," */* "), Conn.setrequestproperty (" Connection "," keep-alive ");  Conn.getresponsecode () = = () {is = Conn.getinputstream (); BAOs = new Bytearrayoutputstream (); int len = -1;byte[] buf = new Byte[128];while (len = Is.read (BUF))! =-1) {baos.write (buf, 0, Len);} Baos.flush (); return baos.tostring ();} Else{throw new RuntimeException ("Responsecode is not 200 ... ");}} catch (Exception e) {e.printstacktrace ();} finally{try{if (Is! = Null) Is.close ();} catch (IOException e) {}try{if (BAOs! = null) Baos.close ();} catch (IOException e) {}conn.disconnect ();} return null;} /** * Request to send a POST method to the specified URL * * @param URL * Send request URL * @param param * Request parameter, request parameter should be Name1=value1&amp ; a form of name2=value2. * @return The response result of the remote resource represented * @throws Exception */public static string doPost (string url, string param) {PrintWriter out = null ; BufferedReader in = null; String result = ""; Try{url realurl = new URL (URL);//connection between Open and URL httpurlconnection conn = (httpurlconnection) realurl.openc Onnection ()///Set Generic request attribute Conn.setrequestproperty ("accept", "*/*") Conn.setrequestproperty ("Connection", " Keep-alive "), Conn.setrequestmethod (" POST "), Conn.setrequestproperty (" Content-type "," application/ X-www-form-urlencoded "); Conn.setrequestproperty (" CharSet "," Utf-8 "); Conn.setusecaches (false);// The Send POST request must be set to the following two lines conn.setdooutput (true); Conn.setdoinput (true); Conn.setreadtimeout (timeout_in_millions); Conn.setconnecttimeout (timeout_in_millions); if (param! = nulL &&!param.trim (). Equals ("")) {//Gets the output stream corresponding to the URLConnection object out = new PrintWriter (Conn.getoutputstream ());// Send request parameter out.print (param);//Flush output stream buffer Out.flush ();} Defines the BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ())); String Line;while (line = In.readline ()) = null) {result + = line;}} catch (Exception e) {e.printstacktrace ();} 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) {ex.printstacktrace ();}} return result;}}


Tool classes related to asynchronous networks Httputils

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.