自己寫的一個請求

自己沒事寫的一個網絡請求的類,處理正確數據和錯誤數據的結果,




1、首先是一個接口類

package com.example.inter;

/**
 * 返回數據接口
 * @author libin
 *
 */
public interface IReceiveData {

	public void setOKData(String okStr); //正確數據
	
	public void setConnectDesc(String conDesc);   //連接超時
	
	public void setErrorData(String errorStr,String errorCode);   //錯誤數據
}

2、公共基礎類


package com.example.request.entity;
/**
 * 請求基礎類
 * @author libin
 *
 */
public class RequestBaseEntity {

	protected String terminalPhysicalNo; // 手機串號
	protected String application; // 應用名稱
	protected String pluginSerialNo;
	protected String pluginVersion;
	protected String terminalOs;
	protected String terminalModel;
	protected String version;

	public RequestBaseEntity(String terminalPhysicalNo, String application) {
		super();
		this.terminalPhysicalNo = terminalPhysicalNo;
		this.application = application;
		pluginSerialNo = "1.0";
		pluginVersion = "1.0.1";
		terminalOs = "Android 2.3";
		terminalModel = "3GW100";
		version = "1.0";
	}

	
}


3、請求類


package com.example.request.entity;




public class CheckLoginRequest extends RequestBaseEntity{


<span style="white-space:pre">	</span>public CheckLoginRequest(String terminalPhysicalNo, String application) {
<span style="white-space:pre">		</span>super(terminalPhysicalNo, application);
<span style="white-space:pre">		</span>// TODO Auto-generated constructor stub
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>


<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>private String mobileNum;


<span style="white-space:pre">	</span>public String getMobileNum() {
<span style="white-space:pre">		</span>return mobileNum;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public void setMobileNum(String mobileNum) {
<span style="white-space:pre">		</span>this.mobileNum = mobileNum;
<span style="white-space:pre">	</span>}


}
4、請求網絡線程

package com.example.asynctask;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
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 org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;

import com.example.inter.IReceiveData;
import com.example.util.SDKUtils;

/**
 * 
 * 請求網絡線程
 * 
 * @author libin
 * 
 */
public class HttpAsyncTask extends AsyncTask<String, Void, String> {

	private static String TAG = "HttpAsyncTask";
	private HttpClient customerHttpClient;
	private final String CHARSET = HTTP.UTF_8;
	private IReceiveData data;

	public HttpAsyncTask(Context context,IReceiveData data) {
		this.data = data;
		SDKUtils.readConfig(context);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}

	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		HttpPost httpPost = new HttpPost(params[0]);
		HttpClient client = getHttpClient();
		String result = null;
		try {
			String strs;
			// 加密 傳過來的json 字符串
			strs = SDKUtils.encode(params[1]);

			StringEntity stringEntity = new StringEntity(strs, HTTP.UTF_8);
			httpPost.setEntity(stringEntity);
			// 有的地方可能會用到userId 或者token

			HttpResponse response = client.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, HTTP.UTF_8);
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 超時
		} catch (IOException e) {
			// TODO Auto-generated catch block
			result = "1";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		// 超時
		if (result != null) {
			if (result.equals("1")) {
				data.setConnectDesc("網絡超時 ,請稍後重試");
			} else {
				// 不超時
				String status = result.substring(0, 1);
				try {
					String str;
					if (status.equals("1")) {
						str = SDKUtils.decode(result);
						Log.i(TAG,"str--->"+ str);
						data.setOKData(str);
					} else {
						String respcode = new String(result.split("\\|")[1]);
						String respdesc = new String(Base64.decode(
								result.split("\\|")[2], Base64.DEFAULT));
						data.setErrorData(respdesc, respcode);
						Log.i(TAG, "respdesc--->" + respdesc + "respcode"
								+ respcode);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public synchronized HttpClient getHttpClient() {
		if (null == customerHttpClient) {
			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, 5000);
			/* 請求超時 */
			HttpConnectionParams.setSoTimeout(params, 10000);

			// 設置我們的HttpClient支持HTTP和HTTPS兩種模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));

			// 使用線程安全的連接管理來創建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			customerHttpClient = new DefaultHttpClient(conMgr, params);
		}
		return customerHttpClient;
	}
}


5、請求的Activity界面,裏面的URL可自行填寫

package com.example.t;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.asynctask.HttpAsyncTask;
import com.example.inter.IReceiveData;
import com.example.request.entity.CheckLoginRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MainActivity extends Activity {

	private Button btn;
	private EditText edit;
	private String url = "url";
	Gson gson;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) this.findViewById(R.id.btn_check);
		edit = (EditText) this.findViewById(R.id.edittext);

		GsonBuilder gb = new GsonBuilder();
		gb.disableHtmlEscaping();
		gson = gb.create(); // 獲取json
		// GetKeyReq getKeyReq = new GetKeyReq("", ""); //實例化對象
		// String gsonStr = gson.toJson(getKeyReq); //生成json

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String phone = edit.getText().toString();

				if (!TextUtils.isEmpty(phone)) {
					CheckLoginRequest checkLoginRequest = new CheckLoginRequest(
							getDeviceId(), "CheckLoginNameExist.Req");
					checkLoginRequest.setMobileNum(phone);
					sendHttpPost(url, gson.toJson(checkLoginRequest));
				}else{
					Toast.makeText(MainActivity.this, "請輸入手機號", 1000)
					.show();

				}
			}
		});

	}

	private void sendHttpPost(String url, String json) {
		new HttpAsyncTask(this, new IReceiveData() {

			@Override
			public void setOKData(String okStr) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "okStr--->" + okStr, 1000)
						.show();
			}

			@SuppressLint("ShowToast")
			@Override
			public void setErrorData(String errorStr, String errorCode) {
				// TODO Auto-generated method stub
				Toast.makeText(
						MainActivity.this,
						"errorStr--->" + errorStr + "errorCode--->" + errorCode,
						1000).show();
			}

			@Override
			public void setConnectDesc(String conDesc) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "conDesc--->" + conDesc, 1000)
						.show();
			}
		}).execute(url, json);
	}

	private String getIMEIString() {
		TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		String szImei = TelephonyMgr.getDeviceId();
		return szImei;
	}

	/**
	 * 獲取mac值
	 * 
	 * @return
	 */
	private String getMacString() {
		WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
		return m_szWLANMAC;
	}

	public String getDeviceId() {
		String m_szLongID = getIMEIString() + "|" + getMacString();
		return m_szLongID;
	}

}


6、界面佈局代碼
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入手機號" />

    <Button
        android:id="@+id/btn_check"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edittext"
        android:text="檢查手機號是否存在" />

</RelativeLayout>






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章