Volley 重写源码,使用Post方式获取网络Json数据

来源:互联网 发布:淘宝交保证金在哪里 编辑:程序博客网 时间:2024/05/22 04:21

最近看了很多Volley的文章,基本上都是使用get方法获取网络Json数据的。但是考虑到网络传输的安全性,还是得硬着头皮先把Volley的源码看得差不多了,再来想想怎么修改源码,让其可以使用post方法获取网络Json数据。在此期间,看了几篇文章,不得不说,人家讲得真好。
http://www.cnblogs.com/bvin/
http://www.eoeandroid.com/forum.php?mod=viewthread&tid=307046
大家可以去看看。实现post方法获取网络数据,还得多亏了aloyise的帖子。废话不多说了。先贴代码吧。
下面的这个demo,服务器端是本地的php服务器,代码大概的意思是返回Json数据数据内容是:

1
{"version":"2","downURL":"http://localhost/file/update/android/yiqi2.apk"}

在Eclipse中,安装好Git之后,克隆(clone)Volley到工作区间。下面,我们来修改Volley源码:
1.Request.java
a. 新增一个Map变量 :

1
private Map<String, String> map;

b.修改getParams()函数:

123
protected Map<String, String> getParams() throws AuthFailureError {        return map;    }

c.为了不破坏原有的Request的构造函数,我们新增两个Request的构造函数:

 1 2 3 4 5 6 7 8 91011
public Request(String url, Response.ErrorListener listener, Map<String, String> map) {        this(Method.DEPRECATED_GET_OR_POST, url, listener, map);    }public Request(int method, String url, Response.ErrorListener listener, Map<String, String> map) {        mMethod = method;        mUrl = url;        mErrorListener = listener;        this.map = map;        setRetryPolicy(new DefaultRetryPolicy());        mDefaultTrafficStatsTag = TextUtils.isEmpty(url) ? 0: Uri.parse(url).getHost().hashCode();    }

2.JsonRequest.java
a.为了不破坏原有的JsonRequest的构造函数,我们新增两个JsonRequest的构造函数:

 1 2 3 4 5 6 7 8 910
public JsonRequest(String url, String requestBody, Listener<T> listener,            ErrorListener errorListener, Map<String, String> map) {        this(Method.DEPRECATED_GET_OR_POST, url, requestBody, listener, errorListener, map);    }public JsonRequest(int method, String url, String requestBody, Listener<T> listener,            ErrorListener errorListener, Map<String, String> map) {        super(method, url, errorListener, map);        mListener = listener;        mRequestBody = requestBody;    }

b.注释掉getPostBodyContentType()、getPostBody()、getBodyContentType()、getBody()方法
3.JsonObjectRequest.java
为了不破坏原有的JsonObjectRequest的构造函数,我们新增两个JsonObjectRequest的构造函数:

 1 2 3 4 5 6 7 8 910
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,            Listener<JSONObject> listener, ErrorListener errorListener, Map<String, String> map) {        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,                    errorListener, map);    }public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener,            ErrorListener errorListener, Map<String, String> map) {        this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,                listener, errorListener, map);    }

这样,我们的Volley源码基本上就改完了。再在Volley所在的工程右键team --> Commit一下。
再新建一个andorid工程,并引用Volley工程。
1.AndroidManifest.xml

 1 2 3 4 5 6 7 8 910111213141516171819202122232425262728
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.volley_sample_one"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="10"        android:targetSdkVersion="17" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.volley_sample_one.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.INTERNET" /></manifest>

2.activity_main.xml

 1 2 3 4 5 6 7 8 910111213141516171819202122
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <Button         android:id="@+id/one"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Get Data From Post"        android:textSize="14sp"        android:gravity="center"/>    <TextView         android:id="@+id/dataList"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textSize="14sp"/></LinearLayout>

3.MainActivity.java

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
package com.volley_sample_one;import java.util.HashMap;import java.util.Map;import org.json.JSONException;import org.json.JSONObject;import com.android.volley.Request.Method;import com.android.volley.RequestQueue;import com.android.volley.Response.ErrorListener;import com.android.volley.Response.Listener;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {    private Button one;    private TextView dataList;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        one = (Button) findViewById(R.id.one);        dataList = (TextView) findViewById(R.id.dataList);        final Listener<JSONObject> responseListener = new Listener<JSONObject>() {             @Override            public void onResponse(JSONObject response) {                dataList.setText(response + "");            }        };        final ErrorListener errorListener = new ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {                dataList.setText(error + "");//              System.out.println(error);            }        };        one.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());                           //String url = "http://192.168.1.112/test/phone.php?action=android&execute=test";                String url = "http://192.168.1.112/test/phone.php";                JsonObjectRequest jsonObjectRequest;                Map<String, String> map = new HashMap<String, String>();                map.put("action", "android");                map.put("execute", "test");                try {            jsonObjectRequest = new JsonObjectRequest(Method.POST, url, null,                         responseListener, errorListener, map);                    requestQueue.add(jsonObjectRequest);                } catch (Exception e) {                    e.printStackTrace();                    System.out.println(e + "");                 }                 requestQueue.start();             }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        menu.add(0, 1, 0, "Exit...");        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId()) {        case 1:            android.os.Process.killProcess(android.os.Process.myPid());            System.exit(0);             break;        default:            break;        }        return super.onOptionsItemSelected(item);    }}

注:使用get()方法请求的地址是这句
String url = "http://192.168.1.112/test/phone.php?action=android&execute=test";

运行的结果:
post.png
界面比较丑陋。=_=。。。
顺便记下来,以后方便看,嘿嘿。。。写得不好,还请各位大神们拍砖,大家交流交流。。

0 0
原创粉丝点击