項目中竟然遇到了這樣的問題,要求客戶端請求的方式爲:參數按照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.csdn.net/walker02/article/details/8105936