您的位置:首页 > 移动开发 > Objective-C

Android Volley框架(一):StringRequest、JsonObjectRequest、JsonArrayRequest

2015-08-11 09:37 561 查看

Volley GET/POST请求的基本步骤:

1. 创建一个RequestQueue对象。

2. 创建一个 StringRequest/JsonObjectRequest/JsonArrayRequest 对象。

3. 将 StringRequest/JsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。

关于JsonObjectRequest的post请求,有时无法正确解析上传的参数,原因在于服务端不接收json请求方式,只接收字符串,即服务端接收字符串,返回json串,这时需改写JsonObjectRequest方法,详见volley_JsonObjectRequestPost2()。

直接上代码,使用说明见注释:

第一步 搭建环境

下载jar包,新建工程,导入volley.jar

第二步 AndroidManifest.xml 文件

打开网络权限 (<uses-permission android:name="android.permission.INTERNET" />)

引入MyApplication (android:name="com.example.volleyfrademo.MyApplication")

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volleyfrademo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:name="com.example.volleyfrademo.MyApplication">
        <activity
            android:name=".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>

</manifest>


第三步 MyApplication.java 文件

package com.example.volleyfrademo;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;

import android.app.Application;
import android.text.TextUtils;

public class MyApplication extends Application {

public static final String TAG = "MyApplication";
private RequestQueue queues;
private static MyApplication instance;

@Override
public void onCreate() {
super.onCreate();
instance = this;
}

public static synchronized MyApplication getInstance() {
return instance;
}

public RequestQueue getRequestQueue(){
if (queues == null) {
queues = Volley.newRequestQueue(getApplicationContext());
}
return queues;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
VolleyLog.d("Adding request to queue: %s", req.getUrl());
getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
if (queues != null) {
queues.cancelAll(tag);
}
}
}


第四步 activity_main.xml 文件

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.volleyfrademo.MainActivity" >

    <TextView
        android:id="@+id/tv_resp1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <Button
        android:id="@+id/btn_get_string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过StringRequest的GET方式请求服务器" />
    
    <Button
        android:id="@+id/btn_post_string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过JsonObjectRequest的POST方式请求服务器" />
    
    <Button
        android:id="@+id/btn_get_jsonobject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过JsonObjectRequest的GET方式请求服务器" />
    
    <Button
        android:id="@+id/btn_post_jsonobject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过JsonObjectRequest的POST方式请求服务器" />
    
    <Button
        android:id="@+id/btn_post_jsonobject2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过JsonObjectRequest的POST方式请求服务器2" />
    
    <Button
        android:id="@+id/btn_get_jsonarray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过JsonArrayRequest的GET方式请求服务器" />

</LinearLayout>


第五步 MainActivity.java文件

package com.example.volleyfrademo;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Volley GET/POST请求的基本步骤:
* 1. 创建一个RequestQueue对象。
* 2. 创建一个 StringRequest/JsonObjectRequest/JsonArrayRequest 对象。
* 3. 将 StringRequest/JsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。
*
* @author jiatao
*/

public class MainActivity extends Activity implements OnClickListener{

private TextView tv_resp1;
private Button btn_get_string, btn_post_string, btn_get_jsonobject, btn_post_jsonobject, btn_post_jsonobject2, btn_get_jsonarray;
private String urlget = "http://gc.ditu.aliyun.com/geocoding?a=苏州市";
private String urlpost = "http://api.24ht.net/app/signin";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setEvent();
}

private void initView() {
tv_resp1 = (TextView) findViewById(R.id.tv_resp1);
btn_get_string = (Button) findViewById(R.id.btn_get_string);
btn_post_string = (Button) findViewById(R.id.btn_post_string);
btn_get_jsonobject = (Button) findViewById(R.id.btn_get_jsonobject);
btn_post_jsonobject = (Button) findViewById(R.id.btn_post_jsonobject);
btn_post_jsonobject2 = (Button) findViewById(R.id.btn_post_jsonobject2);
btn_get_jsonarray = (Button) findViewById(R.id.btn_get_jsonarray);
}

private void setEvent() {
btn_get_string.setOnClickListener(this);
btn_post_string.setOnClickListener(this);
btn_get_jsonobject.setOnClickListener(this);
btn_post_jsonobject.setOnClickListener(this);
btn_post_jsonobject2.setOnClickListener(this);
btn_get_jsonarray.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_get_string:
volley_StringRequestGet();
break;
case R.id.btn_post_string:
volley_StringRequestGetPost();
break;
case R.id.btn_get_jsonobject:
volley_JsonObjectRequestGet();
break;
case R.id.btn_post_jsonobject:
volley_JsonObjectRequestPost();
break;
case R.id.btn_post_jsonobject2:
volley_JsonObjectRequestPost2();
break;
case R.id.btn_get_jsonarray:
volley_JsonArrayRequestGet();
break;
}
}

/*
* StringRequest
* StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
* 这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求.
*
* GET方式请求服务器
*/
private void volley_StringRequestGet() {
StringRequest request = new StringRequest(Method.GET, urlget, new Listener<String>() {
@Override
public void onResponse(String response) {
tv_resp1.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});

request.setTag("volley_StringRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}

/*
* StringRequest
* StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
* 这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求.
*
* POST方式请求服务器
*/
private void volley_StringRequestGetPost() {
StringRequest request = new StringRequest(Method.POST, urlpost, new Listener<String>() {
@Override
public void onResponse(String response) {
tv_resp1.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("user", "jt1024");
map.put("psw", "111111");
return map;
}
};

request.setTag("volley_StringRequestGetPost");
MyApplication.getInstance().addToRequestQueue(request);
}

/*
* JsonObjectRequest
* JsonObjectRequest — To send and receive JSON Object from the Server
* 这个类可以用来发送和接收JSON对象。
* 这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。
*
* GET方式请求服务器
*/
private void volley_JsonObjectRequestGet() {
JsonObjectRequest request = new JsonObjectRequest(Method.GET, urlget, null, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});

request.setTag("volley_JsonObjectRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}

/*
* JsonObjectRequest
* JsonObjectRequest — To send and receive JSON Object from the Server
* 这个类可以用来发送和接收JSON对象。
* 这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。
*
* POST方式请求服务器
*/
private void volley_JsonObjectRequestPost() {
Map<String, String> map = new HashMap<String, String>();
map.put("user", "jt1024");
map.put("psw", "111111");
JSONObject object = new JSONObject(map);

JsonObjectRequest request = new JsonObjectRequest(Method.POST, urlpost, object, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonObjectRequestPost");
MyApplication.getInstance().addToRequestQueue(request);
}

/*
* JsonObjectRequest
* 如果服务端并不支持json的请求方式,比如常见的spring mvc服务端,就很难支持json的请求方式,
* 那么就需要客户端以普通的post方式进行提交,服务端返回json串
* 首先在Activity类里,继承Request实现一个NormalPostRequest类
*
* 服务端不支持json的请求方式
*/
private void volley_JsonObjectRequestPost2() {
String url = "http://api.24ht.net/app/signin";
Map<String, String> map = new HashMap<String, String>();
map.put("user", "jt1024");
map.put("psw", "111111");
JSONObject object = new JSONObject(map);

NormalPostRequest request = new NormalPostRequest(url, map, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});
request.setTag("volley_JsonObjectRequestPost2");
MyApplication.getInstance().addToRequestQueue(request);
}

private void volley_JsonArrayRequestGet() {
JsonArrayRequest request = new JsonArrayRequest(urlget, new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
tv_resp1.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
tv_resp1.setText(error.toString());
}
});

request.setTag("volley_JsonArrayRequestGet");
MyApplication.getInstance().addToRequestQueue(request);
}

}




第六步 NormalPostRequest.java

package com.example.volleyfrademo;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

/**
*
* 对应MainActivity.java中的JsonObjectRequest-POST2:
* 如果服务端并不支持json的请求方式,比如常见的spring mvc服务端,就很难支持json的请求方式,
* 那么就需要客户端以普通的post方式进行提交,服务端返回json串
* 首先在Activity类里,继承Request实现一个NormalPostRequest类
*
* @author jiatao
*
*/
public class NormalPostRequest extends Request<JSONObject>{

private Map<String, String> mMap;
private Listener<JSONObject> mListener;
public NormalPostRequest(String url, Map<String, String> map, Listener<JSONObject> listener,ErrorListener errorListener) {
super(Request.Method.POST, url, errorListener);

mListener = listener;
mMap = map;
}

//mMap是已经按照前面的方式,设置了参数的实例
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return mMap;
}

//此处因为response返回值需要json数据,和JsonObjectRequest类一样即可
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers));

return Response.success(new JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: