Custom HttpURLConnection tool class, httpurlconnection
Public class CustomHttpURLConnection {private static String TAG = "CustomHttpUrlConnection"; private static HttpURLConnection conn; public CustomHttpURLConnection () {} public static String GetFromWebByHttpUrlConnection (String strUrl, NameValuePair... nameValuePairs) {String result = ""; try {URL url = new URL (strUrl); conn = (HttpURLConnection) url. openConnection (); conn. setDoInput (true); conn. setConnectTime Out (3000); conn. setreadtimeouts (4000); conn. setRequestProperty ("accept", "*/*"); // int resCode = conn. getResponseCode (); conn. connect (); InputStream stream = conn. getInputStream (); InputStreamReader inReader = new InputStreamReader (stream); BufferedReader buffer = new BufferedReader (inReader); String strLine = null; while (strLine = buffer. readLine ())! = Null) {result + = strLine;} inReader. close (); conn. disconnect (); return result;} catch (MalformedURLException e) {// TODO Auto-generated catch blockLog. e (TAG, "getFromWebByHttpUrlCOnnection:" + e. getMessage (); e. printStackTrace (); return null;} catch (IOException e) {// TODO Auto-generated catch blockLog. e (TAG, "getFromWebByHttpUrlCOnnection:" + e. getMessage (); e. printStackTrace (); return null ;}} public static String PostFromWebByHttpURLConnection (String strUrl, NameValuePair... nameValuePairs) {String result = ""; try {URL url = new URL (strUrl); conn = (HttpURLConnection) url. openConnection (); // sets whether to read data from httpUrlConnection. The default value is true; conn. setDoInput (true); // set whether to output data to httpUrlConnection. Because this is a post request, the parameter must be placed in the // http body. Therefore, it must be set to true, which is false by default; conn. setDoOutput (true); // set the request method to "POST". The default value is GET conn. setRequestMethod ("POS T "); // set timeout conn. setConnectTimeout (3000); conn. setReadTimeout (4000); // The cache conn cannot be used for Post requests. setUseCaches (false); conn. setInstanceFollowRedirects (true); // set that the transmitted content type is a serializable java object. // (If this option is not set, when the serialized object is transmitted, if the WEB service is not of this type by default, java may be thrown. io. EOFException) conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // connection, from the above 2nd URLs. the current configuration of openConnection () must be completed before connect, // urlConn. connect (); InputStream in = c Onn. getInputStream (); InputStreamReader inStream = new InputStreamReader (in); BufferedReader buffer = new BufferedReader (inStream); String strLine = null; while (strLine = buffer. readLine ())! = Null) {result + = strLine;} return result;} catch (IOException ex) {Log. e (TAG, "PostFromWebByHttpURLConnection:" + ex. getMessage (); ex. printStackTrace (); return null ;}}}