HTTP encapsulation For Android

Source: Internet
Author: User
Tags set cookie

[Java] view plaincopyprint?
Package com. example. mynetutil;
 
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. SocketTimeoutException;
Import java.net. URL;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. Map;
 
Import org. apache. http. Header;
Import org. apache. http. HttpEntity;
Import org. apache. http. HttpResponse;
Import org. apache. http. HttpStatus;
Import org. apache. http. client. entity. UrlEncodedFormEntity;
Import org. apache. http. client. methods. HttpPost;
Import org. apache. http. impl. client. DefaultHttpClient;
Import org. apache. http. message. BasicHeader;
Import org. apache. http. message. BasicNameValuePair;
Import org. apache. http. params. CoreConnectionPNames;
Import org. apache. http. util. EntityUtils;
 
Import android. content. Context;
Import android.net. ConnectivityManager;
Import android.net. NetworkInfo;
Import android. util. Log;
Import android. widget. Toast;
 
/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @ Author sfshine
*
*/
Public class HttpUtil {
 
Private static Header [] headers = new BasicHeader [11];
Private static String TAG = "HTTPUTIL ";
Private static int TIMEOUT = 10*1000;
 
/**
* Your header of http op
*/
Static {
Headers [0] = new BasicHeader ("Appkey ","");
Headers [1] = new BasicHeader ("Udid ","");
Headers [2] = new BasicHeader ("OS ","");
Headers [3] = new BasicHeader ("Osversion ","");
Headers [4] = new BasicHeader ("Appversion ","");
Headers [5] = new BasicHeader ("Sourceid ","");
Headers [6] = new BasicHeader ("Ver ","");
Headers [7] = new BasicHeader ("Userid ","");
Headers [8] = new BasicHeader ("Usersession ","");
Headers [9] = new BasicHeader ("Unique ","");
Headers [10] = new BasicHeader ("Cookie ","");
 
}
 
/**
* Op Http get request
*
* @ Param url
* @ Param map
* Values to request
* @ Return
*/
 
Static public String get (String url, HashMap <String, String> map ){
 
Int I = 0;
For (Map. Entry <String, String> entry: map. entrySet ()){
 
Log. I (TAG, entry. getKey () + "=>" + entry. getValue ());
If (I = 0 ){
Url = url + "? "+ Entry. getKey () +" = "+ entry. getValue ();
} Else {
Url = url + "&" + entry. getKey () + "=" + entry. getValue ();
}
 
I ++;
 
}
String reult = post (url, null );
Return reult;
 
}
 
/**
* Op Http post request, "404 error" response if failed
*
* @ Param url
* @ Param map
* Values to request
* @ Return
*/
 
Static public String post (String url, HashMap <String, String> map ){
 
DefaultHttpClient client = new DefaultHttpClient ();
Client. getParams (). setParameter (CoreConnectionPNames. CONNECTION_TIMEOUT, TIMEOUT );
Client. getParams (). setParameter (CoreConnectionPNames. SO_TIMEOUT, TIMEOUT );
HttpPost post = new HttpPost (url );
Log. I (TAG, url );
Post. setHeaders (headers );
String result = "404 error ";
ArrayList <BasicNameValuePair> pairList = new ArrayList <BasicNameValuePair> ();
If (map! = Null ){
For (Map. Entry <String, String> entry: map. entrySet ()){
Log. I (TAG, entry. getKey () + "=>" + entry. getValue ());
BasicNameValuePair pair = new BasicNameValuePair (
Entry. getKey (), entry. getValue ());
PairList. add (pair );
}
 
}
 
Try {
HttpEntity entity = new UrlEncodedFormEntity (pairList, "UTF-8 ");
Post. setEntity (entity );
HttpResponse response = client.exe cute (post );
If (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK ){
SetCookie (response );
Result = EntityUtils. toString (response. getEntity (), "UTF-8 ");
Log. I (TAG, "result =>" + result );
Return result;
}
}
Catch (Exception e ){

}

Log. e (TAG, result );
Return result;
}
 
/**
* Post Bytes to Server
* @ Param url
* @ Param bytes of text
* @ Return
*/
Public static String PostBytes (String url, byte [] bytes ){
Try {
URL murl = new URL (url );
Final HttpURLConnection con = (HttpURLConnection) murl
. OpenConnection ();
 
Con. setDoInput (true );
Con. setDoOutput (true );
Con. setUseCaches (false );
 
Con. setRequestMethod ("POST ");
Con. setRequestProperty ("Connection", "Keep-Alive ");
Con. setRequestProperty ("Charset", "UTF-8 ");
Con. setRequestProperty ("Content-Type", "text/html ");
String cookie = headers [10]. getValue ();
If (! IsNull (headers [10]. getValue ())){
Con. setRequestProperty ("cookie", cookie );
}

Con. setReadTimeout (TIMEOUT );
Con. setConnectTimeout (TIMEOUT );
Log. I (TAG, url );
DataOutputStream dsDataOutputStream = new DataOutputStream (
Con. getOutputStream ());
DsDataOutputStream. write (bytes, 0, bytes. length );
 
DsDataOutputStream. close ();
If (con. getResponseCode () = HttpStatus. SC _ OK ){
InputStream isInputStream = con. getInputStream ();
Int ch;
StringBuffer buffer = new StringBuffer ();
While (ch = isInputStream. read ())! =-1 ){
Buffer. append (char) ch );
}
 
Log. I (TAG, "GetDataFromServer>" + buffer. toString ());
 
Return buffer. toString ();
} Else {
Returns "404 error ";
}
} Catch (SocketTimeoutException e ){
Return "timeouterror ";
} Catch (IOException e ){
// TODO Auto-generated catch block
Returns "404 error ";
}
}
 
/**
* Set Cookie
*
* @ Param response
*/
Private static void setCookie (HttpResponse response ){
If (response. getHeaders ("Set-Cookie"). length> 0 ){
Log. d (TAG, response. getHeaders ("Set-Cookie") [0]. getValue ());
Headers [10] = new BasicHeader ("Cookie ",
Response. getHeaders ("Set-Cookie") [0]. getValue ());
}
}
 
/**
* Check net work
*
* @ Param context
* @ Return
*/
Public static boolean hasNetwork (Context context ){
ConnectivityManager con = (ConnectivityManager) context
. GetSystemService (Context. CONNECTIVITY_SERVICE );
NetworkInfo workinfo = con. getActiveNetworkInfo ();
If (workinfo = null |! Workinfo. isAvailable ()){
Toast. makeText (context, "No network connection currently, please try again later", Toast. LENGTH_SHORT). show ();
Return false;
}
Return true;
}
/***
* @ Category check if the string is null
* @ Return true if is null
**/
Public static boolean isNull (String string ){
Boolean t1 = "". equals (string );
Boolean t2 = string = null;
Boolean t3 = string. equals ("null ");
If (t1 | t2 | t3 ){
Return true;
} Else {
Return false;
}
}
}

Test
[Java]
Package com. example. mynetutil;
 
Import java. util. HashMap;
 
Import android. OS. Bundle;
Import android. app. Activity;
Import android. view. Menu;
Import android. view. MenuItem;
Import android. support. v4.app. NavUtils;
 
Public class MainActivity extends Activity {
 
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
String url = "http: // 192.168.1.77/zwork/test. php ";
HashMap <String, String> map = new HashMap <String, String> ();
Map. put ("goods_id", "100078 ");
Map. put ("cat_id", "100088 ");
HttpUtil. get (url, map );
 
}
 
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
GetMenuInflater (). inflate (R. menu. activity_main, menu );
Return true;
}
 
}

 

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.