自己写的一个请求
2015-11-02 17:19
330 查看
自己没事写的一个网络请求的类,处理正确数据和错误数据的结果,
1、首先是一个接口类
2、公共基础类
3、请求类
5、请求的Activity界面,里面的URL可自行填写
6、界面布局代码
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>
相关文章推荐
- 预测产品的分词结果、相似度降序排序.
- 开发注意点
- python数据结构学习笔记-4-堆栈 队列
- C#第三天
- 第九周项目3-(1)稀疏矩阵的三元组表示
- android 模拟滑动事件
- 用lua 下载文件小示例
- 第十周项目3—利用二叉树遍历思想解决问题
- Qt Pro
- Linux文件系统简介
- c语言总结
- 400
- Uncaught TypeError: a.beginBulkUpdate is not a function
- Android自定义View之图形图像工具类Path的特殊用法
- 第九周项目4-广义表算法库及应用(2)
- hdu 5536 Chip Factory 2015长春区域赛 数据结构 Trie
- 阻塞非阻塞,同步与异步
- 漫谈 C++ 智能指针 01
- C#第二天
- 021.数组的二分查找