Android中利用HttpClient建立一次持久的连接
生活随笔
收集整理的這篇文章主要介紹了
Android中利用HttpClient建立一次持久的连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先,http協議是無狀態的連接,之前的兩種方式get,與post連接方式,每點擊一次就啟動了一個線程,而在啟動線程時
很自然的就重新的new出了一個新的HttpClient,相當于兩個客戶端向服務器發送了請求,這在實際應用中顯然是不合理的,由
于Android中沒有瀏覽器類似的Cookie管理機制,所以我們必須保證在Android客戶端啟動之后,我們對服務器訪問的是同一個
Client。這里用到的思想主要是單例,加上同步機制,以下是一個簡單的實現案例:
MainActivity.java:
package com.example.test003;import java.io.InputStream; import java.util.ArrayList; import java.util.List;import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject;import com.example.test003.MainActivity;import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;public class MainActivity extends Activity {private EditText et1;private EditText et2;private Button btn1;private Button btn2;private TextView tv3;private Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et1 = (EditText) super.findViewById(R.id.editText1);et2 = (EditText) super.findViewById(R.id.editText2);tv3 = (TextView)super.findViewById(R.id.textView3);btn1 = (Button)super.findViewById(R.id.button1);btn2 = (Button)super.findViewById(R.id.button2);handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 1:try {JSONObject obj = (JSONObject) msg.obj;String result = obj.getString("result");if(result.equals("1")){Toast.makeText(MainActivity.this, "歡迎您"+obj.getString("cname"),3000).show();}else{Toast.makeText(MainActivity.this, "登陸失敗",3000).show();}} catch (JSONException e) {// TODO Auto-generated catch block e.printStackTrace();}break;case 2:String info = (String) msg.obj;Toast.makeText(MainActivity.this, info,3000).show();break;}}};btn2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubInputStream iis = YcHttpClient.post("http://192.168.14.194:8080/HttpClient_Server/back/index.jsp", null);byte[] bs = IOUtil.read(iis);String s = new String(bs);Message m = new Message();m.what = 2;m.obj = s;handler.sendMessage(m);}}).start();}});btn1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubString cname = et1.getText().toString().trim();String password = et2.getText().toString().trim();String op = "login";List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("cname", cname));params.add(new BasicNameValuePair("password", password));params.add(new BasicNameValuePair("op",op));InputStream iis = YcHttpClient.post(Constants.ADDRESS, params);try {byte[] bs = IOUtil.read(iis);String s = new String(bs);JSONObject obj = new JSONObject(s);Message m = new Message();m.what = 1;m.obj = obj;handler.sendMessage(m);} catch (JSONException e) {// TODO Auto-generated catch block e.printStackTrace();}}}).start();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}}UserHttpClient.java:
package com.example.test003;import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List;import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; 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.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerParams; 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.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP;import android.util.Log; /*** 單例模式,為解決Http協議無狀態,模擬一次持久的鏈接狀態* 構造方法私有化 對外提供一個getHttpClient方法,* 并且讓這個方法同步,來解決多線程訪問的問題* @author dell**/ public class UserHttpClient {private static final String CHARSET = HTTP.UTF_8;private static HttpClient userHttpClient;private static final String TAG = "userHttpClient";//構造方法私有化private UserHttpClient() {}//對外提供getHttpClient方法public static synchronized HttpClient getHttpClient() {//如果userHttpClient == null 即原來沒有 userHttpClient 第一次鏈接if (null == userHttpClient) {// This interface represents a collection of HTTP protocol parameters//這是一個Http協議的集合,里面存放了Http協議的相應參數信息HttpParams params = new BasicHttpParams();// 設置一些基本參數HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //設置協議的版本HttpProtocolParams.setContentCharset(params, CHARSET); //設置內容的編碼集HttpProtocolParams.setUseExpectContinue(params, true); // HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");// 超時設置/* 從連接池中取連接的超時時間 */ConnManagerParams.setTimeout(params, 1000);/* 連接超時 */HttpConnectionParams.setConnectionTimeout(params, 2000);/* 請求超時 */HttpConnectionParams.setSoTimeout(params, 4000);// 設置我們的HttpClient支持HTTP和HTTPS兩種模式SchemeRegistry schReg = new SchemeRegistry();schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));// 使用線程安全的連接管理來創建HttpClientClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);userHttpClient = new DefaultHttpClient(conMgr, params);}return userHttpClient;}/*** * @param url:訪問的地址* @param params :要傳的參數* @return :服務器返回一個輸入流*/public static InputStream post(String url, List<NameValuePair> params) {try {// 編碼參數List<NameValuePair> formparams = new ArrayList<NameValuePair>(); // 請求參數if (params != null && params.size() > 0) {for (NameValuePair p : params) {formparams.add(p);}}//創建一個實體,里面存放了要傳送的數據 并且對數據進行了編碼 :CHARSET -- > utf-8UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, CHARSET);// 創建POST請求HttpPost request = new HttpPost(url);//在請求里把要傳送的數據放進去 request.setEntity(entity);// 獲取唯一的一個HttpClient實例... 單例模式HttpClient client = getHttpClient();HttpResponse response = client.execute(request);if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {throw new RuntimeException("請求失敗");}HttpEntity resEntity = response.getEntity();return (resEntity == null) ? null : resEntity.getContent();} catch (UnsupportedEncodingException e) {Log.w(TAG, e.getMessage());return null;} catch (ClientProtocolException e) {Log.w(TAG, e.getMessage());return null;} catch (IOException e) {throw new RuntimeException("連接失敗", e);}} }IOUtil.java:
package com.example.test003;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;public class IOUtil {public static byte[] read(InputStream inputStream){byte[] buffer = new byte[1024];int length = 0;ByteArrayOutputStream baos = new ByteArrayOutputStream();try {while ((length = inputStream.read( buffer,0,buffer.length)) != -1){baos.write(buffer,0,length);inputStream.close();}} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();}return baos.toByteArray();} }Constants.java:
package com.example.test003;public class Constants {public final static String ADDRESS = "http://192.168.14.194:8080/HttpClient_Server/cust.action"; }?
?
?
?
轉載于:https://www.cnblogs.com/EmperLin/p/3497881.html
總結
以上是生活随笔為你收集整理的Android中利用HttpClient建立一次持久的连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu10.04系统调试TQ244
- 下一篇: Session丢失,都是CDN惹的祸