且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

区分不同手机平台客户端

更新时间:2021-08-19 09:38:51

 Conclusion  : Unlike User-Agent ,which let the browser describe its meta data and information , the two kinds of client by default will not have a pre-defined field which can function like this.

 

Solution: (We created a self-defined field in the http header)

For example ,we create a field named Mobile-Agent

 

In client side:

when we construct the http request ,we add the value of header “Mobile-Agent” to be some value

Android Client code only need to  set the “Mobile-Agent” header to be ” Android”.

Code example:  (see my highlighted)



  1. public JSONObject callJSONWebService(String url) { 
  2.  
  3.             HttpParams my_httpParams = new BasicHttpParams(); 
  4.  
  5.             HttpConnectionParams.setConnectionTimeout(my_httpParams, conn_timeout); 
  6.  
  7.             HttpConnectionParams.setSoTimeout(my_httpParams, conn_timeout); 
  8.  
  9.             
  10.  
  11.             HttpClient httpClient = new DefaultHttpClient(my_httpParams); 
  12.  
  13.             HttpGet httpRequest = new HttpGet(url); 
  14.  
  15.   
  16.  
  17.             httpRequest.setHeader("User-Agent","bleum agent"); 
  18.  
  19.             httpRequest.setHeader(“Mobile-Agent”,”Android”); 
  20.  
  21.             HttpResponse httpResponse = null
  22.  
  23.             
  24.  
  25.             JSONObject httpJsonResult = null
  26.  
  27.             String result = null
  28.  
  29.             try { 
  30.  
  31.                   httpResponse = httpClient.execute(httpRequest); 
  32.  
  33.                   if(httpResponse.getStatusLine().getStatusCode() == 200){ 
  34.  
  35.                         HttpEntity httpEntity = httpResponse.getEntity(); 
  36.  
  37.                         if(httpEntity != null){ 
  38.  
  39.                               InputStream inputStream = httpEntity.getContent(); 
  40.  
  41.                               result = this.convertStreamToString(inputStream); 
  42.  
  43.                               httpJsonResult = new JSONObject(result); 
  44.  
  45.                               inputStream.close(); 
  46.  
  47.                         } 
  48.  
  49.                   } 
  50.  
  51.             } catch (Exception e) { 
  52.  
  53.                   System.out.println("call JsonWebService failed."); 
  54.  
  55.                   e.printStackTrace(); 
  56.  
  57.             } 
  58.  
  59.             httpClient.getConnectionManager().shutdown(); 
  60.  
  61.             return httpJsonResult; 
  62.  
  63.       } 
  64.  
  65.   

 

IPhone Client code can use Objective-C to do the similar thing ,just set the “Mobile-Agent” header to be “IPhone

 

In server side’s servlet :

we only use the Servlet API to resolve “Mobile-Agent” field.

 

Then solved.





本文转自 charles_wang888 51CTO博客,原文链接:http://blog.51cto.com/supercharles888/835904,如需转载请自行联系原作者