Android client uses HttpClient to initiate web Data Access

Source: Internet
Author: User
Tags set cookie setcookie

Android client uses HttpClient to initiate web Data Access

Data Interaction Between HttpClient and the server: HttpPost and HttpGet correspond to Post and Get submission respectively. For the sake of being an Android client, you must implement data interaction between the client and the server to ensure smooth data chains and closed data loops. Because no permissions have been set for the Android client to access web data before, the system resources can be accessed well. However, if this method is used to develop applications, there will be a great security risk, A Host or Get can be obtained after the data is submitted, and the web terminal system is completely streaking. Therefore, permission management on the web end is necessary, so you do not have to worry too much about the security risks caused by the Android client. Android beginners generally encounter problems when learning. The first two days ago, they encountered the problem that the web Client Set permissions and the Android client initiated access to obtain data.

 

1. HttpPost and HttpGet implement user logon and list display

Compile a test Activity, MainActivity.

 

Package com. boonya. httpclienttest; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. unsupportedEncodingException; import java. util. arrayList; import java. util. hashMap; import java. util. list; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; 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. message. basicNameValuePair; import org. apache. http. protocol. HTTP; import org. json. JSONArray; import org. json. JSONObject; import com. boonya. httpclienttest. utils. htttpClientUtil; import android. app. activity; import android. OS. bundle; import android. util. log; import android. widget. listView; import android. widget. simpleAdapter; import android. widget. toast; public class MainActivity extends Activity {private static final String TAG = MainActivity; private List
 
  
> Videos = null; private HashMap
  
   
Video = null; private ListView listView = null; private static String loginurl = http: // 192.168.1.147: 8090/wtms/androidservice/login; private static String getdataurl = http: // 192.168.1.147: 8090/wtms/androidservice/videos. avd; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); listView = (ListView) findViewById (R. id. videos); postMeth Od (); getMethod ();}/*** http get server data display ** @ param url */protected void getMethod () {HttpGet request = new HttpGet (getdataurl ); // request. setHeader (Cookie, HtttpClientUtil. getCookie (); // set cookie try {// Set request Parameter items // request. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); HttpClient client = HtttpClientUtil. getInstance (); // execute the request and return the corresponding HttpResponse response = client.exe cute (request); // determine whether the request is successful F (response. getStatusLine (). getStatusCode () = 200) {// 200 indicates that the request is successful. StringBuilder builder = new StringBuilder (); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (response. getEntity (). getContent (); String s = null; while (s = bufferedReader. readLine ())! = Null) {builder. append (s);} // String out = EntityUtils. toString (entity, UTF-8); String msg = builder. toString (); Log. d (log, >>> execution method getMethod () to get the range value: + msg); JSONArray jsonArray = new JSONArray (msg); videos = new ArrayList
   
    
> (); For (int I = 0; I <jsonArray. length (); I ++) {JSONObject jsonObject = (JSONObject) jsonArray. get (I); int id = jsonObject. getInt (id); String name = jsonObject. getString (name); int timelength = jsonObject. getInt (time); video = new HashMap
    
     
(); Video. put (id, id); video. put (name, name); video. put (timelength, duration: + timelength); videos. add (video);} SimpleAdapter adapter = new SimpleAdapter (this, videos, R. layout. item, new String [] {name, timelength}, new int [] {R. id. title, R. id. timelength}); listView. setAdapter (adapter) ;}} catch (Exception e) {e. printStackTrace (); Log. e (TAG, e. toString (); Toast. makeText (MainActivity. this, failed to get data, Toast. LENGTH_LONG ). show () ;}/ *** HttpPost submit data */@ SuppressWarnings ({unchecked, rawtypes}) protected void postMethod () {try {// use the ApacheHttp client to connect (important method) HttpClient client = HtttpClientUtil. getInstance (); // create an HttpGet object if the Get object is submitted; otherwise, create an HttpPost object // The method for submitting the POST: HttpPost request = new HttpPost (loginurl ); // if it is Post submission, You can encapsulate the parameters in the set and pass List params = new ArrayList (); params. add (new BasicNameValuePair (username, test); params. add (new BasicNameValuePair (password, test); // UrlEncodedFormEntity is used to convert a set to an Entity Object request. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); try {// get the corresponding message HttpResponse response = client.exe cute (request); StringBuilder builder = new StringBuilder (); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (response. getEntity (). getContent (); // operation cookie/* List
     
      
Cookies = (AbstractHttpClient) client). getCookieStore (). getCookies (); if (cookies! = Null & cookies. size ()> 0) {for (int I = 0; I <cookies. size (); I ++) {HtttpClientUtil. setCookie (cookies. get (I ). getValue () ;}} */String s = null; while (s = bufferedReader. readLine ())! = Null) {builder. append (s);} String string = builder. toString (); Log. d (log, >>>> execution method postMethod () to get the range value: + string);} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} catch (UnsupportedEncodingException e) {e. printStackTrace ();}}}
     
    
   
  
 

 

2. Implement cookie sharing between the client and the server

Here, the HttpClient object is unique on the Android client in the single-sample mode. After a user logs on to the system, this object records the user's Cookie. Once access authentication is established between the client and the server, in the future, you can send any HTTP request to the server or perform resource operations.

 

Package com. boonya. httpclienttest. utils; import org. apache. http. client. httpClient; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. basicHttpParams; import org. apache. http. params. httpConnectionParams; public class HtttpClientUtil {/** Set Request timeout for 10 seconds */private static final int REQUEST_TIMEOUT = 10*1000; /** set the data wait time-out time to 10 seconds */private static final int SO_TIMEOUT = 10*1000; private static HttpClient instance;/** remember cookie String */private static String cookie; /*** custom method: Initialize HttpClient and set timeout ** @ return: HttpClient object */private HtttpClientUtil () {} public static String getCookie () {return cookie;} public static void setCookie (String cookie) {HtttpClientUtil. cookie = cookie;} public static HttpClient getInstance () {if (instance = null) {BasicHttpParams httpParams = new BasicHttpParams (); HttpConnectionParams. setConnectionTimeout (httpParams, REQUEST_TIMEOUT); HttpConnectionParams. setSoTimeout (httpParams, SO_TIMEOUT); instance = new DefaultHttpClient (httpParams);} return instance ;}}
The cookie field above is not mandatory. If HttpClient is not a Singleton, you need to remember the cookie after logon in static variables.

 

How to obtain HttpClientUtil cookies is optimized:

 

Package com. boonya. httpclienttest. utils; import java. util. list; import org. apache. http. client. httpClient; import org. apache. http. cookie. cookie; import org. apache. http. impl. client. abstractHttpClient; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. basicHttpParams; import org. apache. http. params. httpConnectionParams; public class HtttpClientUtil {/** Set Request timeout for 10 seconds */private static final int REQUEST_TIMEOUT = 10*1000; /** set the wait data timeout time to 10 seconds */private static final int SO_TIMEOUT = 10*1000; private static HttpClient instance; /** remember cookie String */private static String cookie = null;/*** custom method: Initialize HttpClient and set timeout ** @ return: httpClient object */private HtttpClientUtil () {} public static String getCookie () {// make sure the instance has HtttpClientUtil. getInstance (); // get cookieList
 
  
Cookies = (maid) instance). getCookieStore (). getCookies (); if (cookies! = Null & cookies. size ()> 0) {for (int I = 0; I <cookies. size (); I ++) {cookie = cookies. get (I ). getValue () ;}return cookie;} public static HttpClient getInstance () {if (instance = null) {BasicHttpParams httpParams = new BasicHttpParams (); HttpConnectionParams. setConnectionTimeout (httpParams, REQUEST_TIMEOUT); HttpConnectionParams. setSoTimeout (httpParams, SO_TIMEOUT); instance = new DefaultHttpClient (httpParams);} return instance ;}}
 


 

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.