Android tool class -------) Http request tool class

Source: Internet
Author: User

Android tool class -------) Http request tool class

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; // public class HttpUtils {private static final int TIMEOUT_IN_MILLIONS = 5000; public interface CallBack {void onRequestComplete (String result);}/*** asynchronous Get request ** @ Param urlStr * @ param callBack */public static void doGetAsyn (final String urlStr, final CallBack callBack) {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 (final String urlStr, final String params, final CallBack callBack) throws Exception {new Thread () {public void run () {try {String result = doPost (urlStr, params); if (callBack! = Null) {callBack. onRequestComplete (result) ;}} catch (Exception e) {e. printStackTrace ();}};}. start ();}/*** Get request to obtain returned 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. setReadTi Meout (TIMEOUT_IN_MILLIONS); conn. setConnectTimeout (TIMEOUT_IN_MILLIONS); conn. setRequestMethod ("GET"); conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); if (conn. getResponseCode () = 200) {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;}/*** send a POST method request to a specified URL ** @ param url * The request URL * @ param * request parameter, the request parameters should be in the form of name1 = value1 & name2 = value2. * @ Return indicates the response result of the Remote resource * @ throws Exception */public static String doPost (String url, String param) {PrintWriter out = null; BufferedReader in = null; string result = ""; try {URL realUrl = new URL (url); // open the connection with the URL HttpURLConnection conn = (HttpURLConnection) realUrl. openConnection (); // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setReque StMethod ("POST"); conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); conn. setRequestProperty ("charset", "UTF-8"); conn. setUseCaches (false); // The following two rows of conn must be set to send a POST request. setDoOutput (true); conn. setDoInput (true); conn. setReadTimeout (TIMEOUT_IN_MILLIONS); conn. setConnectTimeout (TIMEOUT_IN_MILLIONS); if (param! = Null &&! Param. trim (). equals ("") {// get the output stream of the URLConnection object out = new PrintWriter (conn. getOutputStream (); // sends the request parameter out. print (param); // flush the Buffer out of the output stream. flush ();} // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line; while (line = in. readLine ())! = Null) {result + = line;} catch (Exception e) {e. printStackTrace () ;}// use finally blocks to close the output stream and input stream finally {try {if (out! = Null) {out. close () ;}if (in! = Null) {in. close () ;}catch (IOException ex) {ex. printStackTrace () ;}} return result ;}}

Related Article

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.