public class Customhttpurlconnection {private static String TAG = "Customhttpurlconnection";p rivate static HttpURLConnection conn;public customhttpurlconnection () {}public static string getfromwebbyhttpurlconnection (string Strurl,namevaluepair. Namevaluepairs) {String result= ""; try {URL url = new URL (strurl); conn = (httpurlconnection) URL.O Penconnection (); Conn.setdoinput (true); Conn.setconnecttimeout (+); conn.setreadtimeout (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) {//TODOAuto-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 ();//settings are read from HttpURLConnection, true by default; Conn.setdoinput (TRUE);//Set whether to output to httpurlconnection, because this is a POST request, the parameters are placed in//HTTP body, so it needs to be set to True, by default is false; Conn.setdooutput (TRUE);//The method to set the request is "POST", the default is Get Conn.setrequestmethod ("post");//Set timeout Conn.setconnecttimeout (3000) ; conn.setreadtimeout (4000);//Post request cannot use cache Conn.setusecaches (false); Conn.setinstancefollowredirects (true);// Sets the content type of the transfer to be a serializable Java object//(if this item is not set, when the serialized object is transferred, the Web service may throw java.io.EOFException when the default is not this type) Conn.setrequestproperty (" Content-type "," application/x-www-form-urlencoded ");//connection, url.openconnection () from the above 2nd () the configuration must be done before connect,// Urlconn.connect (); InputStream in = Conn.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;}}}
Customizing the HttpURLConnection tool class