网络发送参数拼接与Http异步任务回调打包(二)

来源:互联网 发布:centos 6.5 分区方案 编辑:程序博客网 时间:2024/05/20 06:23

     根据上一篇文章,接下来来封装http连接网络的代码,仅供参考

     Http封装的get与post方法

<pre name="code" class="java">package com.qq.wx.voice.demo;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import org.json.JSONException;import org.json.JSONObject;import android.os.AsyncTask;import android.util.Log;public class HttpGetPost {private AsyncTaskCallback mCallback;public void onGet(String url,RequestParams params,AsyncTaskCallback Callback){mCallback=Callback;MyAsyTaskGet myAsyTask=new MyAsyTaskGet();myAsyTask.execute(url,params.toString());}public void onPost(String url,RequestParams params,AsyncTaskCallback Callback){mCallback=Callback;MyAsyTaskPost myAsyTask=new MyAsyTaskPost();myAsyTask.execute(url,params.toString());}public class MyAsyTaskPost extends AsyncTask<String, Integer, String>{private Throwable mThrowable=new Throwable();private AsyncTaskCallback mCallback;@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubString url=params[0];String urlParams=params[1];String returnCode = "";DataOutputStream outStream=null;byte [] bs=urlParams.getBytes();try {URL u=new URL(url);HttpURLConnection urlConnection=(HttpURLConnection) u.openConnection();urlConnection.setDoOutput(true);urlConnection.setConnectTimeout(15*1000);urlConnection.setUseCaches(false);urlConnection.setRequestMethod("POST");urlConnection.setRequestProperty("Connection", "Keep-Alive");urlConnection.setRequestProperty("Charset", "UTF-8");urlConnection.setRequestProperty("Content-Length",String.valueOf(bs.length));urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");outStream = new DataOutputStream(urlConnection.getOutputStream());outStream.write(bs);outStream.flush();if(urlConnection.getResponseCode()==200){StringBuffer mBuffer=new StringBuffer();String read="";BufferedReader reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));while((read=reader.readLine())!=null){mBuffer.append(read);}returnCode=mBuffer.toString();}} catch (MalformedURLException e) {// TODO Auto-generated catch blockLog.i("values", "returnCode:"+e.getMessage());mThrowable=e;returnCode="1";e.printStackTrace();e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();Log.i("values", "returnCode:"+e.getMessage());mThrowable=e;returnCode="1";e.printStackTrace();}finally{try {outStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return returnCode;}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubif (!result.equals("1") && !result.equals("")) {try {new JSONObject(result);} catch (JSONException e) {mThrowable = new Throwable("JSONException:服务器返回的JSON数据格式有误!");result = mThrowable.getMessage();Log.e("asyresult", result);mCallback.onFail(mThrowable, result);e.printStackTrace();return;}Log.i("asyresult", result);mCallback.onSuccess(0, result);} else{mCallback.onFail(mThrowable, mThrowable.getMessage());}}}public class MyAsyTaskGet extends AsyncTask<String, Integer, String>{private Throwable mThrowable=new Throwable();private AsyncTaskCallback mCallback;@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stubString url=params[0];String urlParams=params[1];String returnCode = "";DataOutputStream outStream=null;byte [] bs=urlParams.getBytes();try {URL u=new URL(url);HttpURLConnection urlConnection=(HttpURLConnection) u.openConnection();urlConnection.setDoOutput(true);urlConnection.setConnectTimeout(15*1000);urlConnection.setUseCaches(false);outStream= new DataOutputStream(urlConnection.getOutputStream());outStream.write(bs);outStream.flush();if(urlConnection.getResponseCode()==200){StringBuffer mBuffer=new StringBuffer();String read="";BufferedReader reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));while((read=reader.readLine())!=null){mBuffer.append(read);}returnCode=mBuffer.toString();}} catch (MalformedURLException e) {// TODO Auto-generated catch blockLog.i("values", "returnCode:"+e.getMessage());mThrowable=e;returnCode="1";e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();Log.i("values", "returnCode:"+e.getMessage());mThrowable=e;returnCode="1";}finally{try {outStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return returnCode;}@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubif (!result.equals("1") && !result.equals("")) {try {new JSONObject(result);} catch (JSONException e) {mThrowable = new Throwable("JSONException:服务器返回的JSON数据格式有误!");result = mThrowable.getMessage();Log.e("asyresult", result);mCallback.onFail(mThrowable, result);e.printStackTrace();return;}Log.i("asyresult", result);mCallback.onSuccess(0, result);} else{mCallback.onFail(mThrowable, mThrowable.getMessage());}}}}


自己写的回调函数


public interface AsyncTaskCallback {/* * 异步任务的三个方法 *///请求成功调用此方法public void onSuccess(int position,String result);    //请求失败调用此方法public void onFail(Throwable throwable,String result);}

上篇封装好的拼接参数

package com.qq.wx.voice.demo;import java.util.HashMap;  import java.util.Map.Entry;  import java.util.Set;  public class RequestParams {  private HashMap<String, String> params;  public RequestParams() {  params = new HashMap<String, String>();  }  public void put(String key, String value) {  params.put(key, value);  }  @Override  public String toString() {  //将map集合放到set中  Set<Entry<String, String>> entries = params.entrySet();  StringBuilder builder = new StringBuilder();  //循环将set数据取出来追加在builder里  for (Entry<String, String> entry : entries) {  builder.append(entry.getKey() + "=" + entry.getValue() + "&");  }  if (!builder.equals("") &&builder.toString().contains("&") ) {  builder.deleteCharAt(builder.lastIndexOf("&"));  }  return builder.toString();  }  public HashMap<String, String> getParams() {  return params;  }  }  

在Activity中实现  很方便的

package com.qq.wx.voice.demo;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;public class MyActivity extends Activity{@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);String url="http://127.0.0.1:8088/login.aspx";RequestParams params=new RequestParams();params.put("pwd", "123");params.put("uid", "123");HttpGetPost mGetPost=new HttpGetPost();mGetPost.onGet(url, params, new AsyncTaskCallback() {@Overridepublic void onSuccess(int position, String result) {// TODO Auto-generated method stub/* * 这里的result就是访问取到的数据,如果是json可以直接解析了 */try {JSONObject object=new JSONObject(result);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void onFail(Throwable throwable, String result) {// TODO Auto-generated method stub}});}}

这样的封装用Http去访问数据时不容易出错  而且直接掉get  或者post方法去访问数据   是不是很方便哈.具体GET POST里的方法根据公司需求  自己封装   仅给大家提供这个思路。


0 0
原创粉丝点击