Android-Encapsulated HTTP request Utility Class _android

Source: Internet
Author: User
Tags readline


Copy Code code as follows:

Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.net.URLEncoder;
Import Java.security.KeyStore;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;

Import Org.apache.http.HttpResponse;
Import org.apache.http.HttpVersion;
Import org.apache.http.client.HttpClient;
Import org.apache.http.client.entity.UrlEncodedFormEntity;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.client.methods.HttpPost;
Import Org.apache.http.conn.ClientConnectionManager;
Import org.apache.http.conn.scheme.PlainSocketFactory;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.scheme.SchemeRegistry;
Import org.apache.http.conn.ssl.SSLSocketFactory;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
Import Org.apache.http.message.BasicNameValuePair;
Import Org.apache.http.params.BasicHttpParams;
Import Org.apache.http.params.HttpParams;
Import Org.apache.http.params.HttpProtocolParams;
Import Org.apache.http.protocol.HTTP;
Import org.apache.http.util.EntityUtils;

Import Android.content.Context;
Import Android.net.ConnectivityManager;

/**
* Network Tool class
*
* @author Malinkang
*
*/

public class NetUtils {
/**
* Determine the status of the network connection
*
* @return True, available; false, not available
*/
public static Boolean Isopennetwork (context context) {
Connectivitymanager Connmanager = (connectivitymanager) context
. Getsystemservice (Context.connectivity_service);
if (connmanager.getactivenetworkinfo ()!= null) {
Return Connmanager.getactivenetworkinfo (). isavailable ();
}

return false;
}

/**
* GET Request
*
* @param urlstring
* @param params
* @return
*/
public static string Getrequest (String urlstring, map<string, string> params) {

try {
StringBuilder UrlBuilder = new StringBuilder ();
Urlbuilder.append (urlstring);

if (null!= params) {

Urlbuilder.append ("?");

iterator<entry<string, string>> iterator = Params.entryset ()
. iterator ();

while (Iterator.hasnext ()) {
entry<string, string> param = Iterator.next ();
UrlBuilder
. Append (Urlencoder.encode (Param.getkey (), "UTF-8"))
. Append (' = ')
. Append (Urlencoder.encode (Param.getvalue (), "UTF-8"));
if (Iterator.hasnext ()) {
Urlbuilder.append (' & ');
}
}
}
Creating HttpClient Objects
HttpClient client = Getnewhttpclient ();
Send GET request Create HttpGet Object
HttpGet GetMethod = new HttpGet (urlbuilder.tostring ());
HttpResponse response = Client.execute (GetMethod);
Get Status Code
int res = Response.getstatusline (). Getstatuscode ();
if (res = = 200) {

                StringBuilder Builder = new StringBuilder ();
               //Get response content
                BufferedReader Reader = new BufferedReader (
                         New InputStreamReader (Response.getentity (). GetContent ())) ;

for (String s = reader.readline (); s!= null; s = Reader
. ReadLine ()) {
Builder.append (s);
}
return builder.tostring ();
}
catch (Exception e) {

}

return null;
}

/**
* POST Request
*
* @param urlstring
* @param params
* @return
*/
public static string Postrequest (String urlstring,
List<basicnamevaluepair> params) {

try {
1. Creating HttpClient Objects
HttpClient client = Getnewhttpclient ();
2. Send GET request Create HttpGet Object
HttpPost Postmethod = new HttpPost (urlstring);
Postmethod.setentity (New urlencodedformentity (params, HTTP). Utf_8));
HttpResponse response = Client.execute (Postmethod);
int statuecode = Response.getstatusline (). Getstatuscode ();
if (Statuecode = = 200) {
System.out.println (Statuecode);
Return entityutils.tostring (Response.getentity ());
}
catch (Exception e) {

}

return null;
}

When saving + the number of seconds at that time,
public static long expires (String second) {
Long L = long.valueof (second);

Return L * 1000L + system.currenttimemillis ();
}

private static HttpClient getnewhttpclient () {
try {
KeyStore Truststore = keystore.getinstance (KeyStore
. Getdefaulttype ());
Truststore.load (null, NULL);

Sslsocketfactory SF = new Sslsocketfactoryex (Truststore);
Sf.sethostnameverifier (Sslsocketfactory.allow_all_hostname_verifier);

Httpparams params = new Basichttpparams ();
Httpprotocolparams.setversion (params, httpversion.http_1_1);
Httpprotocolparams.setcontentcharset (params, HTTP. UTF_8);

Schemeregistry Registry = new Schemeregistry ();
Registry.register (New Scheme ("http", Plainsocketfactory
. Getsocketfactory (), 80));
Registry.register (New Scheme ("https", SF, 443));

Clientconnectionmanager ccm = new Threadsafeclientconnmanager (
params, registry);

return new Defaulthttpclient (CCM, params);
catch (Exception e) {
return new Defaulthttpclient ();
}
}
}

Another packaged get request that has recently been used:

Copy Code code as follows:

public class Httputils {

Private final static String TAG = "Easytokensevice";
Private final static int connectiontimeout = 5000;
private static InputStream InputStream = null;
private static String urlstr = null;
private static Boolean isconnecting;

/**
* Encapsulate HTTP GET requests
*
* @param URL
* @return is
*/
public static InputStream get (String url) throws IOException, Exception {

urlstr = URL;
Isconnecting = true;

HttpGet httpget = new HttpGet (URLSTR);
Httpparams httpparameters = new Basichttpparams ();
Httpconnectionparams.setconnectiontimeout (Httpparameters,
ConnectionTimeout);

Defaulthttpclient httpclient = new Defaulthttpclient (httpparameters);
HttpResponse response = Httpclient.execute (HttpGet);

if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
httpentity entity = response.getentity ();
InputStream = Entity.getcontent ();
return InputStream;}
else return null;




}
}

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.