android http post 请求与 json字符串
一、目标
android客户端发送一个json格式的http的请求,期望得到服务端的一个json反馈。
1. 客户端发送的json格式为:
{"data" : "valueString"}
2. 服务端发送的json格式:
{
"errorCode" : "valueString",
"entries":[
{
"name":"海底捞",
"phone":"18800000110",
"url":"http://cater.haidilao.com/Cater/wap/index.action"
},
{
"name":"峨眉山",
"phone":"18800000119",
"url":"http://51youhui.baidu.com/emeishan"
},
...
{
"name":"中公教育",
"phone":"18800000666",
"url":"http://m.offcn.com"
}
]
}
3. 其中 json中映射的实体类类型定义如下:
public class Entry {
// 用戶名
private String name;
// 用戶号码
private String phone;
// 用户主页网址
private String url;
public Entry() {
}
public Entry(String name, String phone, String url) {
super();
this.name = name;
this.phone = phone;
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isSupportZhiDaHao() {
return this.url != null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
二、引用包前提条件:
1. android客户端:
没有额外的包以来,所依赖的json包都包含在android sdk的org.json包下。
2 .服务端:
commons-beanutils-1.9.2.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
下载参考:http://www.mvnrepository.com/
三、客户端代码
1. android 客户端发送请求时的代码(使用httpClient):
// 测试服务器所在的项目URL
final String SERVER_URL = "http://172.22.148.49:8080/TestHttp/TestHttp";
HttpPost postRequest = new HttpPost(SERVER_URL);
// 构造请求的json串
JSONObject para = new JSONObject();
para.put("data", numStr);
StringEntity entity = new StringEntity(para.toString(), "utf-8");
HttpClient client = new DefaultHttpClient();
postRequest.setEntity(entity);
HttpResponse response = client.execute(postRequest);
2.android 客户端接受并解析服务端返回请求的json值:
List<Entry> items = new ArrayList<Entry>();
// 从response中读取所有字符格式的返回值
String entityString = EntityUtils.toString(response.getEntity());
// 将字符格式的返回值,映射成Json对象
JSONObject resJsonObj = new JSONObject(entityString);
// 尝试读取返回的json值中的statusCode字段
if (resJsonObj.getString(statusCode) == null
|| resJsonObj.getString(STATUS_CODE).isEmpty()
|| !resJsonObj.getString(STATUS_CODE).equals("ok")) {
return;
}
// 尝试解析所有以json数组形式返回的json对象
JSONArray entiesArray = resJsonObj.getJSONArray("entries");
for (int i = 0; i < entiesArray.length(); i++) {
JSONObject json = entiesArray.getJSONObject(i);
item = new Entry();
item.setName(json.getString("name"));
item.setPhonenum(json.getString("phone"));
item.setHomePageSites(json.getString("url"));
items.add(item);
}
四、服务端代码
1. 读取客户端的http请求,并解析出json参数(servlet 的doPost方法中):
// 答应http请求中的参数
String acceptjson = "";
BufferedReader br = new BufferedReader(new InputStreamReader(
request.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
br.close();
acceptjson = sb.toString();
String data = "";
JSONObject jo = JSONObject.fromObject(acceptjson);
data = jo.getString("data");
System.out.println("客戶端传来的参数为" + data);
2. 服务端完成针对请求参数中指定的值的处理后,决定返回上面我们约定的json格式json串:
// 创建json根对象
JSONObject mJson = new JSONObject();
// 创建json跟对象的子对象,里面存放对个实体类的值的json数组
JSONArray jsonArray = new JSONArray();
mJson.put("statusCode", "ok");
for (Entry entry : entries) {
if (!entry.getPhone().contains(data))
continue;
JSONObject json = new JSONObject();
json.put("name", entry.getName());
json.put("phone", entry.getPhone());
json.put("url", entry.getUrl());
jsonArray.add(json);
}
mJson.put("entries", jsonArray);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(mJson.toString());
五、注意事项(待续。。。)
1. 编码格式问题
2. android中HttpClient请求并发问题
3.http请求中一些参数的详解和设置
4. android 发https 请求
android http post 请求与 json字符串的更多相关文章
- Android okHttp网络请求之Json解析
前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...
- wemall app商城源码中基于JAVA通过Http请求获取json字符串的代码
wemall-mobile是基于WeMall的Android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.分享其中关于通过Http请求获取json字符串的代码供 ...
- ajax请求返回json字符串/json对象 处理
1. 返回json字符串如何处理 $.ajax({ url:xxx, success:function(date){ }, error:function(){ } }); 通过最原始的返回: Prin ...
- ajax post 请求发送 json 字符串
$.ajax({ // 请求方式 type:"post", // contentType contentType:"application/json", // ...
- ajax请求返回Json字符串运用highcharts数据图表展现数据
[1].[图片] Json字符串和highcharts数据图表展现.jpg 跳至 [1] code=26754#44745" rel="nofollow"> [2] ...
- 【Android进阶】Gson解析json字符串的简单应用
在客户端与服务器之间进行数据传输,一般采用两种数据格式,一种是xml,一种是json.这两种数据交换形式各有千秋,比如使用json数据格式,数据量会比较小,传输速度快,放便解析,而采用xml数据格式, ...
- android通过httpClient请求获取JSON数据并且解析
使用.net创建一个ashx文件,并response.write json格式 public void ProcessRequest(HttpContext context) { context.R ...
- post请求参数Json字符串包含数组的校验和处理 -工作随记-备查工具
package com.xxxx.live.webapp.selvert; import java.io.BufferedReader; import java.io.IOException; imp ...
- post请求参数Json字符串包含数组的校验和处理
传入参数类型 {"aaa":"aaaa","bbb":"bbb","ccc":"ccc&q ...
随机推荐
- Problem C: 更改大小写
#include<stdio.h> int main() { ; ]; gets(a); while(a[i]!='\0') { ; ++i; } printf("%s" ...
- NOIP2014 解题报告·水渣记
Day 1: 第一次参加noip.小激动,小紧张,这些正常的情绪就不用说了.唯一值得一提的是 我早上步行去郑大工学院的时候迷路了,直接转进了隔壁的河南农大,绕了半天找不到机房,还给几个同学打了电话可就 ...
- python基础之条件判断和循环
1.条件判断 age = 3 if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid' ...
- Educational Codeforces Round 8 F. Bear and Fair Set 最大流
F. Bear and Fair Set 题目连接: http://www.codeforces.com/contest/628/problem/F Description Limak is a gr ...
- selenium+python自动化88-批量操作循环点击报错:Element not found in the cache - perhaps the page has changed since it was looked up
前言 selenium定位一组元素,批量操作循环点击的时候会报错:Element not found in the cache - perhaps the page has changed since ...
- 两篇整合Activiti Modeler到业务系统
1. 无法进入editor. http://localhost:8080/YouPRJ/modeler/service/editor?id=2050,前提是这个id必需存在与act_re_model表 ...
- MySQL建表时,日期时间类型选择
MySQL(5.5)所支持的日期时间类型有:DATETIME. TIMESTAMP.DATE.TIME.YEAR. 几种类型比较如下: 日期时间类型 占用空间 日期格式 最小值 最大值 零值表示 D ...
- 隐藏系统EFI分区Z盘
找到C:\Windows\System32\cmd.exe程序, 右键单击cmd 选择以管理员身份运行, 打开命令提示符,输入以下命令(不区分大小写)DiskPart回车List空格volume回车s ...
- Appium处理滑动方法是swipe
滑动API:Swipe(int start x,int start y,int end x,int y,duration) 解释: int start x-开始滑动的x坐标:int start y - ...
- 【4.29安恒杯】writeup
#### 安恒杯_writeup 下面为比赛中做出的题目 MISC: SHOW ME THE FLAG-by-cyyzore CRYPTO: LAZYATTACK-by-GoldsNow 这一题非常巧 ...