上一篇简单了解了Volley的源码 Volley源码简读
本博客代码下载 点击打开链接,免积分下载
ps一下:那个封装头体的请求,url我修改了端口(因为是上线项目,避免外来请求,不过有log日志可以参考)
今天我来简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json
Volley请求有StringRequest、JsonRequest、ImageRequest,这篇文章就精简下,现在公司的网络请求一般都是传给服务器Json格式的数据,然后获取Json格式的数据,进行封装,我这篇就直接用StringRequest请求了,当然JsonRequest对处理Json的返回数据或许效率更好
我们先看看Volley的StringRequest的源码如下:
public class StringRequest extends Request {
private final Listener mListener;
public StringRequest(int method, String url, Listener listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
}
public StringRequest(String url, Listener listener, ErrorListener errorListener) {
this(Method.GET, url, listener, errorListener);
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
}
我们看看这代码,很显然没有做到如何进行对返回的数据,比如Json格式的数据,进行进一步的封装为对象,考虑到封装对象有
fastson、Gson、还有JsonReader都可以,我这篇博客是用的Gson来进行解析json的,主要是方便了代码,毕竟Gson也是谷歌出的。
package com.example.saflyvolley;
import java.io.UnsupportedEncodingException;
import android.util.Log;
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;
import com.example.saflyvolley.safinterface.UIDataListener;
import com.google.gson.Gson;
public class SaflyBaseRequest extends Request {
private Gson mGson;
private final Listener mListener;
private Class mClass;
public SaflyBaseRequest(int method, String url, Class clazz,
Listener listener, ErrorListener errorListener) {
super(method, url, errorListener);
mGson = new Gson();
mClass = clazz;
mListener = listener;
}
/**
* 默认get方式
*/
public SaflyBaseRequest(String url, Class clazz, Listener listener,
ErrorListener errorListener) {
this(Method.GET, url, clazz, listener, errorListener);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.i("Safly", "jsonString-->>"+jsonString);
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
mGson = new Gson();
mClass = clazz;
这是新增的,在parseNetworkResponse中
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
将原始的,替换为上面的,意思就是将封装好的对象,提供给外部接口使用
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
下面这行代码是一个Json数据的接口
http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly
{
"resultcode": "101",
"reason": "错误的请求KEY!",
"result": null,
"error_code": 10001
}
我们对此创建对象,以及set get方法(省略了)
private String resultcode;
private String reason;
private String result;
private int error_code;
public interface UIDataListener {
public void onErrorHappened(String errorMessage);
public void onDataChanged(T data);
}
public void onResponse(ResponseMsg responseMsg) {
if (uiResponseMsgDataListener != null) {
notifyDataChanged(responseMsg);
}
}
protected void notifyDataChanged(T data) {
if (uiResponseMsgDataListener != null) {
if (data instanceof ResponseMsg) {
uiResponseMsgDataListener.onDataChanged((ResponseMsg) data);
}
}
}
然后在主界面进行接口回调即可
/**
* 封装完毕后的监听,设置界面
*/
@Override
public void onDataChanged(ResponseMsg responseMsg) {
Log.i("Safly", "" + responseMsg.getError_code());
Log.i("Safly", "" + responseMsg.getReason());
Log.i("Safly", "" + responseMsg.getResult());
Log.i("Safly", "" + responseMsg.getResultcode());
}
我们在看下Post方式,进行添加params-->>phone=13429667914&key=safly
http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly
SaflyRequestController saflyRequestController = new SaflyRequestController();
Map map = new HashMap();
map.put("phone", "13429667914");
map.put("key", "safly");
saflyRequestController.RequestType(SaflyRequestController.RequestPost,
map);
saflyRequestController.setUiDataListener(this);
@Override
protected Map getParams()
throws AuthFailureError {
return map;
}
Volley为请求头、请求体添加Json格式的数据
由于下面的代码是不能实现的,我就在定义了一个接口public class MainActivity extends Activity implements
UIDataListener, UIDataListener {
接口如下
public interface UIImplHeadBodyDataListener {
public void onErrorHappened(String errorMessage);
public void UIImplHeadBodyDataChange(T data);
}
Gson、fastson、JsonObject都可以,我们这篇博客用下Gson、JsonObject
首先看我公司的传给服务器的Json数据
{
"Request": {
"head": {
"app_type": "3",
"os_type": "android",
"osversion": "5.1.1",
"appversion": "1.0",
"devicefactory": "LGE",
"devicemodel": "AOSP on HammerHead"
},
"body": {
"phoneimei": "353490061934846",
"context": "反馈"
}
}
}
我们分析那个Json数据,看看需要创建什么样的对象呢?(省略了get 、set方法)
public class RequestBean {
private Request Request;
public RequestBean() {
super();
}
public RequestBean(Request request) {
super();
this.Request = request;
}
public Request getRequest() {
return Request;
}
public void setRequest(Request request) {
this.Request = request;
}
// ///////////////HeadHead//////////////////
public static class Head {
private String app_type;
private String os_type;
private String osversion;
private String appversion;
private String devicefactory;
private String devicemodel;
public Head(String app_type, String os_type, String osversion,
String appversion, String devicefactory, String devicemodel) {
super();
this.app_type = app_type;
this.os_type = os_type;
this.osversion = osversion;
this.appversion = appversion;
this.devicefactory = devicefactory;
this.devicemodel = devicemodel;
}
public Head() {
super();
}
}
////////////////BodyBody/////////////////////
public static class Body {
private String phoneimei;
private String context;
public Body(String phoneimei, String context) {
super();
this.phoneimei = phoneimei;
this.context = context;
}
public Body() {
super();
// TODO Auto-generated constructor stub
}
}
//////////////////RequestRequest/////////////////////////
public static class Request {
private Head head;
private Body body;
public Request(Head head, Body body) {
super();
this.head = head;
this.body = body;
}
}
}
如下就是gson生成的json格式
RequestBean msg = new RequestBean();
RequestBean.Head head = new RequestBean.Head("3", "android", "5.1.1",
"1.0", "LGE", "AOSP on HammerHead");
RequestBean.Body body = new RequestBean.Body("353490061934846", "反馈");
RequestBean.Request request = new RequestBean.Request(head, body);
msg.setRequest(request);
Gson gson = new Gson();
String requestMsg = gson.toJson(msg);
private String createJson() throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONObject body = new JSONObject();
body.put("phoneimei", "353490061934846");
body.put("context", "反馈");
JSONObject head = new JSONObject();
head.put("app_type", "3");
head.put("os_type", "android");
head.put("osversion", "5.1.1");
head.put("appversion", "1.0");
head.put("devicefactory", "LGE");
head.put("devicemodel", "AOSP on HammerHead");
JSONObject Request = new JSONObject();
Request.put("body", body);
Request.put("head", head);
jsonObject.put("Request", Request);
return jsonObject.toString();
}
@Override
public Map getHeaders()
throws AuthFailureError {
Map headers = new HashMap();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", "application/x-javascript");
headers.put("Accept-Encoding", "gzip,deflate");
return headers;
}
@Override
public String getBodyContentType() {
return String.format("application/x-www-form-urlencoded; charset=%s", "utf-8");
}
@Override
public byte[] getBody() throws AuthFailureError {
// TODO Auto-generated method stub
return requestStringBytes;
}
以下是我公司的返回的json,
{"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}}
package com.example.saflyvolley.bean;
/**
* onResponse {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}}
*
*/
public class ResponseBean {
private Response Response;
public ResponseBean() {
super();
}
public ResponseBean(Response response) {
super();
this.Response = response;
}
public Response getResponse() {
return Response;
}
public void setResponse(Response response) {
this.Response = response;
}
// /////////////////////////////
public static class Response {
private Head head;
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public Response(Head head) {
super();
this.head = head;
}
}
// onResponse
// {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}}
public static class Head {
private String statuscode;
private String statusmsg;
public String getStatuscode() {
return statuscode;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
public String getStatusmsg() {
return statusmsg;
}
public void setStatusmsg(String statusmsg) {
this.statusmsg = statusmsg;
}
public Head(String statuscode, String statusmsg) {
super();
this.statuscode = statuscode;
this.statusmsg = statusmsg;
}
public Head() {
super();
}
}
}
以上就是volley的封装,生成json,然后重写请求头体,然后封装对象,以下是代码区
#################################代码区 代码区 代码区############################
SaflyApplication
package com.example.saflyvolley;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.telephony.TelephonyManager;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class SaflyApplication extends Application {
private TelephonyManager telephonyManager;
private static RequestQueue requestQueue;
private static SaflyApplication instance;
@Override
public void onCreate() {
super.onCreate();
this.instance = this;
requestQueue = Volley.newRequestQueue(getApplicationContext());
initHttps();
}
public static SaflyApplication getInstance() {
return instance;
}
public static RequestQueue getRequestQueue() {
return requestQueue;
}
private void initHttps() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactoryEx sf = new SSLSocketFactoryEx(trustStore);
HttpsURLConnection.setDefaultSSLSocketFactory(sf.getSSLContext()
.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Exception e) {
}
}
static class SSLSocketFactoryEx extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
public SSLContext getSSLContext() {
return sslContext;
}
}
}
package com.example.saflyvolley;
import java.io.UnsupportedEncodingException;
import android.util.Log;
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;
import com.example.saflyvolley.safinterface.UIDataListener;
import com.google.gson.Gson;
public class SaflyBaseRequest extends Request {
private Gson mGson;
private final Listener mListener;
private Class mClass;
public SaflyBaseRequest(int method, String url, Class clazz,
Listener listener, ErrorListener errorListener) {
super(method, url, errorListener);
mGson = new Gson();
mClass = clazz;
mListener = listener;
}
/**
* 默认get方式
*/
public SaflyBaseRequest(String url, Class clazz, Listener listener,
ErrorListener errorListener) {
this(Method.GET, url, clazz, listener, errorListener);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.i("Safly", "jsonString-->>"+jsonString);
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
ResponseMsg
package com.example.saflyvolley.bean;
//{"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}
public class ResponseMsg {
private String resultcode;
private String reason;
private String result;
private int error_code;
public String getResultcode() {
return resultcode;
}
public void setResultcode(String resultcode) {
this.resultcode = resultcode;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public ResponseMsg() {
super();
}
public ResponseMsg(String resultcode, String reason, String result,
int error_code) {
super();
this.resultcode = resultcode;
this.reason = reason;
this.result = result;
this.error_code = error_code;
}
}
package com.example.saflyvolley.safinterface;
public interface UIDataListener {
public void onErrorHappened(String errorMessage);
public void onDataChanged(T data);
}
SaflyRequestController
package com.example.saflyvolley;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.example.saflyvolley.bean.ResponseBean;
import com.example.saflyvolley.bean.ResponseMsg;
import com.example.saflyvolley.safinterface.UIDataListener;
public class SaflyRequestController {
public static final int RequestGet = 1;
public static final int RequestPost = 2;
public static final String stringUrlNoParams = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=safly";
public static final String stringUrlWithParams = "http://apis.juhe.cn/mobile/get?";
/**
* 封装对象完毕的接口监听
*/
private UIDataListener uiResponseMsgDataListener;
public void setUiDataListener(
UIDataListener uiResponseMsgDataListener) {
this.uiResponseMsgDataListener = uiResponseMsgDataListener;
}
protected void notifyDataChanged(T data) {
if (uiResponseMsgDataListener != null) {
if (data instanceof ResponseMsg) {
uiResponseMsgDataListener.onDataChanged((ResponseMsg) data);
}
}
}
protected void notifyErrorHappened(String errorMessage) {
if (uiResponseMsgDataListener != null) {
uiResponseMsgDataListener.onErrorHappened(errorMessage);
}
}
/**
* 請求方式
*/
public void RequestType(int getRequestType, final Map map) {
SaflyBaseRequest request;
switch (getRequestType) {
// GET請求
case RequestGet:
request = new SaflyBaseRequest(Method.GET,
stringUrlNoParams, ResponseMsg.class,
new Listener() {
@Override
public void onResponse(ResponseMsg responseMsg) {
if (uiResponseMsgDataListener != null) {
notifyDataChanged(responseMsg);
}
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (uiResponseMsgDataListener != null) {
String message = volleyError.getMessage();
Log.i("Safly", "message-->>" + message);
notifyErrorHappened(message);
}
}
});
SaflyApplication.getRequestQueue().add(request);
break;
// POST請求
case RequestPost:
request = new SaflyBaseRequest(Method.POST,
stringUrlWithParams, ResponseMsg.class,
new Listener() {
@Override
public void onResponse(ResponseMsg responseMsg) {
if (uiResponseMsgDataListener != null) {
notifyDataChanged(responseMsg);
}
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (uiResponseMsgDataListener != null) {
String message = volleyError.getMessage();
Log.i("Safly", "message-->>" + message);
notifyErrorHappened(message);
}
}
}) {
@Override
protected Map getParams()
throws AuthFailureError {
return map;
}
};
SaflyApplication.getRequestQueue().add(request);
break;
default:
break;
}
}
}
RequestBean
package com.example.saflyvolley.bean;
/**
* {"Request": { "head": { "app_type": "3", "os_type": "android", "osversion":
* "5.1.1", "appversion": "1.0", "devicefactory": "LGE", "devicemodel":
* "AOSP on HammerHead" }, "body": { "phoneimei": "353490061934846", "context":
* "反馈" } } }
*/
public class RequestBean {
private Request Request;
public RequestBean() {
super();
}
public RequestBean(Request request) {
super();
this.Request = request;
}
public Request getRequest() {
return Request;
}
public void setRequest(Request request) {
this.Request = request;
}
// /////////////////////////////////
public static class Head {
private String app_type;
private String os_type;
private String osversion;
private String appversion;
private String devicefactory;
private String devicemodel;
public String getApp_type() {
return app_type;
}
public void setApp_type(String app_type) {
this.app_type = app_type;
}
public String getOs_type() {
return os_type;
}
public void setOs_type(String os_type) {
this.os_type = os_type;
}
public String getOsversion() {
return osversion;
}
public void setOsversion(String osversion) {
this.osversion = osversion;
}
public String getAppversion() {
return appversion;
}
public void setAppversion(String appversion) {
this.appversion = appversion;
}
public String getDevicefactory() {
return devicefactory;
}
public void setDevicefactory(String devicefactory) {
this.devicefactory = devicefactory;
}
public String getDevicemodel() {
return devicemodel;
}
public void setDevicemodel(String devicemodel) {
this.devicemodel = devicemodel;
}
public Head(String app_type, String os_type, String osversion,
String appversion, String devicefactory, String devicemodel) {
super();
this.app_type = app_type;
this.os_type = os_type;
this.osversion = osversion;
this.appversion = appversion;
this.devicefactory = devicefactory;
this.devicemodel = devicemodel;
}
public Head() {
super();
// TODO Auto-generated constructor stub
}
}
public static class Body {
private String phoneimei;
private String context;
public Body(String phoneimei, String context) {
super();
this.phoneimei = phoneimei;
this.context = context;
}
public Body() {
super();
// TODO Auto-generated constructor stub
}
public String getPhoneimei() {
return phoneimei;
}
public void setPhoneimei(String phoneimei) {
this.phoneimei = phoneimei;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
}
public static class Request {
private Head head;
private Body body;
public Request(Head head, Body body) {
super();
this.head = head;
this.body = body;
}
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
}
}
package com.example.saflyvolley.bean;
/**
* onResponse {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}}
*
*/
public class ResponseBean {
private Response Response;
public ResponseBean() {
super();
}
public ResponseBean(Response response) {
super();
this.Response = response;
}
public Response getResponse() {
return Response;
}
public void setResponse(Response response) {
this.Response = response;
}
// /////////////////////////////
public static class Response {
private Head head;
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public Response(Head head) {
super();
this.head = head;
}
}
// onResponse
// {"Response":{"head":{"statuscode":"000000","statusmsg":"sucess"}}}
public static class Head {
private String statuscode;
private String statusmsg;
public String getStatuscode() {
return statuscode;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
public String getStatusmsg() {
return statusmsg;
}
public void setStatusmsg(String statusmsg) {
this.statusmsg = statusmsg;
}
public Head(String statuscode, String statusmsg) {
super();
this.statuscode = statuscode;
this.statusmsg = statusmsg;
}
public Head() {
super();
}
}
}
package com.example.saflyvolley.safinterface;
public interface UIImplHeadBodyDataListener {
public void onErrorHappened(String errorMessage);
public void UIImplHeadBodyDataChange(T data);
}
package com.example.saflyvolley;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.example.saflyvolley.bean.ResponseBean;
import com.example.saflyvolley.safinterface.UIDataListener;
import com.example.saflyvolley.safinterface.UIImplHeadBodyDataListener;
public class SaflyRequestImplHeadOrBodyController {
private String url = "https://www.imlianxi.com:xxxx/AppFeedback";
/**
* 封装对象完毕的接口监听
*/
private UIImplHeadBodyDataListener uiResponseBeanDataListener;
public void setUIImplHeadBodyDataListener(UIImplHeadBodyDataListener uiResponseBeanDataListener) {
this.uiResponseBeanDataListener = uiResponseBeanDataListener;
}
protected void notifyDataChanged(T data) {
if (uiResponseBeanDataListener != null) {
if (data instanceof ResponseBean) {
uiResponseBeanDataListener.UIImplHeadBodyDataChange((ResponseBean) data);
}
}
}
protected void notifyErrorHappened(String errorMessage) {
if (uiResponseBeanDataListener != null) {
uiResponseBeanDataListener.onErrorHappened(errorMessage);
}
}
/**
*封装头部 体部 post方式
*/
public void RequestTypeWithRequestHeadAndBody(final byte[] requestStringBytes) {
SaflyBaseRequest request;
request = new SaflyBaseRequest(
Method.POST, url, ResponseBean.class,
new Listener() {
@Override
public void onResponse(ResponseBean responseBean) {
if (uiResponseBeanDataListener != null) {
notifyDataChanged(responseBean);
}
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (uiResponseBeanDataListener != null) {
String message = volleyError.getMessage();
Log.i("Safly", "message-->>" + message);
notifyErrorHappened(message);
}
}
}) {
@Override
public Map getHeaders()
throws AuthFailureError {
Map headers = new HashMap();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", "application/x-javascript");
headers.put("Accept-Encoding", "gzip,deflate");
return headers;
}
@Override
public String getBodyContentType() {
return String.format("application/x-www-form-urlencoded; charset=%s", "utf-8");
}
@Override
public byte[] getBody() throws AuthFailureError {
// TODO Auto-generated method stub
return requestStringBytes;
}
};
SaflyApplication.getRequestQueue().add(request);
}
}
package com.example.saflyvolley;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.example.saflyvolley.bean.RequestBean;
import com.example.saflyvolley.bean.ResponseBean;
import com.example.saflyvolley.bean.ResponseMsg;
import com.example.saflyvolley.safinterface.UIDataListener;
import com.example.saflyvolley.safinterface.UIImplHeadBodyDataListener;
import com.google.gson.Gson;
/**
* {"resultcode":"101","reason":"错误的请求KEY!","result":null,"error_code":10001}
*/
/**
{"Request": { "head": { "app_type": "3", "os_type": "android", "osversion":
"5.1.1", "appversion": "1.0", "devicefactory": "LGE", "devicemodel":
"AOSP on HammerHead" }, "body": { "phoneimei": "353490061934846", "context":
"反馈" } } }
*/
public class MainActivity extends Activity implements
UIDataListener, UIImplHeadBodyDataListener {
private String createJson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* post請求
*/
SaflyRequestController saflyRequestController = new SaflyRequestController();
Map map = new HashMap();
map.put("phone", "13429667914");
map.put("key", "safly");
saflyRequestController.RequestType(SaflyRequestController.RequestPost,
map);
saflyRequestController.setUiDataListener(this);
/**
* get請求
*/
saflyRequestController.RequestType(SaflyRequestController.RequestGet,
null);
/**
* 重寫header body
* 利用Gson生成Json格式请求服务器
*/
RequestBean msg = new RequestBean();
RequestBean.Head head = new RequestBean.Head("3", "android", "5.1.1",
"1.0", "LGE", "AOSP on HammerHead");
RequestBean.Body body = new RequestBean.Body("353490061934846", "反馈");
RequestBean.Request request = new RequestBean.Request(head, body);
msg.setRequest(request);
Gson gson = new Gson();
String requestMsg = gson.toJson(msg);
byte[] requestStringBytes = null;
try {
requestStringBytes = requestMsg.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.i("Safly", "Gson str:" + requestMsg);
SaflyRequestImplHeadOrBodyController saflyRequestImplHeadOrBodyController = new SaflyRequestImplHeadOrBodyController();
saflyRequestImplHeadOrBodyController
.RequestTypeWithRequestHeadAndBody(requestStringBytes);
saflyRequestImplHeadOrBodyController
.setUIImplHeadBodyDataListener(this);
/**
* 利用JsonObject生成json请求服务器
*/
try {
createJson = createJson();
} catch (JSONException e) {
e.printStackTrace();
}
String requestMsgByJsonObject = createJson;
Log.i("Safly", "JsonObject str:" + requestMsgByJsonObject);
}
private String createJson() throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONObject body = new JSONObject();
body.put("phoneimei", "353490061934846");
body.put("context", "反馈");
JSONObject head = new JSONObject();
head.put("app_type", "3");
head.put("os_type", "android");
head.put("osversion", "5.1.1");
head.put("appversion", "1.0");
head.put("devicefactory", "LGE");
head.put("devicemodel", "AOSP on HammerHead");
JSONObject Request = new JSONObject();
Request.put("body", body);
Request.put("head", head);
jsonObject.put("Request", Request);
return jsonObject.toString();
}
/**
* 封装完毕后的监听,设置界面
*/
@Override
public void onDataChanged(ResponseMsg responseMsg) {
Log.i("Safly", "" + responseMsg.getError_code());
Log.i("Safly", "" + responseMsg.getReason());
Log.i("Safly", "" + responseMsg.getResult());
Log.i("Safly", "" + responseMsg.getResultcode());
}
/**
* 服务器返回失败的监听
*/
@Override
public void onErrorHappened(String errorMessage) {
}
@Override
public void UIImplHeadBodyDataChange(ResponseBean data) {
Log.i("Safly", "" + data.getResponse().getHead().getStatuscode());
Log.i("Safly", "" + data.getResponse().getHead().getStatusmsg());
}
}