项目中竟然遇到了这样的问题,要求客户端请求的方式为:参数按照json序列化,然后使用post方式传递给服务器。第一次看到这个东东有点一头雾水,刚开始开发的时候全部使用的get请求方式,因为当时公司不考虑数据安全问题。后来使用了post方式,使用到了session。这下倒好接触了序列化json,然后post方式提交。
首先需要引用谷歌的gson.jar文件,这里面有一些序列化参数的方法,我用到的比较简单直接使用了tojson(类名字); 定义最外层的类PostArgs:
public class PostArgs {
public BaseRequest baseRequest;
public String newsId;
}里面嵌套BaseRequest类,
public class BaseRequest {
public String action;
public String version;
public UserInfo userInfo;
}接着是第三层UserInfo类:
public class UserInfo {
public String userId;
public String userName;
}
在主程序里测试为:
PostArgs postArgs = new PostArgs();
BaseRequest baseRequest = new BaseRequest();
UserInfo userInfo = new UserInfo();
userInfo.userId = "walker";
baseRequest.action = "getAction";
baseRequest.version = "1.1.1";
postArgs.baseRequest = baseRequest;
postArgs.newsId = "1000.1";
baseRequest.userInfo = userInfo;
Gson gson = new Gson();
System.out.println(gson.toJson(postArgs));
输出结果为:
{"baseRequest":{"action":"getAction","userInfo":{"userId":"walker"},"version":"1.1.1"},"newsId":"1000.1"}
/*
* post请求,
*/
public static String post(String httpUrl, String parMap,Context context)
{
System.out.println("post:"+httpUrl);
InputStream input = null;//输入流
InputStreamReader isr = null;
BufferedReader buffer = null;
StringBuffer sb = null;
String line = null;
AssetManager am = null;//资源文件的管理工具类
try {
/*post向服务器请求数据*/
HttpPost request = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonArgs);
request.setEntity(se);
HttpResponse response = new DefaultHttpClient().execute(request);
int code = response.getStatusLine().getStatusCode();
System.out.println("postCode= " + code);
// 若状态值为200,则ok
if (code == HttpStatus.SC_OK) {
//从服务器获得输入流
input = response.getEntity().getContent();
isr = new InputStreamReader(input);
buffer = new BufferedReader(isr,10*1024);
sb = new StringBuffer();
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
}
} catch (Exception e) {
//其他异常同样读取assets目录中的"local_stream.xml"文件
System.out.println("HttpClient post 数据异常");
e.printStackTrace();
return null;
} finally {
try {
if(buffer != null) {
buffer.close();
buffer = null;
}
if(isr != null) {
isr.close();
isr = null;
}
if(input != null) {
input.close();
input = null;
}
} catch (Exception e) {
}
}
System.out.println("PostData:"+sb.toString());
return sb.toString();
}
关键语句就两行:
StringEntity se = new StringEntity(jsonArgs);
request.setEntity(se);
new一个StringEntity,然后把这个当做request的参数设置进去就OK了。
现在客户端基本上返回值基本上也是json格式的值了,post之后返回的字段就可以使用反序列化的方式了。参考http://blog.youkuaiyun.com/walker02/article/details/8105936
1038



被折叠的 条评论
为什么被折叠?



