json串拼写 key=关键字 value=值 例:登陆串
userString = "eche.lau@gmail.com";
password = "111111";
JSONStringer userInfo = new JSONStringer().object()
.key("email").value(userString)
.key("password").value(password).endObject();
JSONStringer json = new JSONStringer().object().key("request").value(userInfo).endObject();
拼写完成的格式是:
{
request => {
:email => "eche.lau@gmail.com",
:password => "111111"
}
}
发送json格式请求方法
public static JSONObject getJsonRequest(String url, Object json) {
HttpPost request = new HttpPost(url);
String retSrc = null;
JSONObject result = null;
try {
StringEntity se = new StringEntity(json.toString(), HTTP.UTF_8);
//设置类型 编码
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(se);
// 发送请求
HttpResponse httpResponse = new DefaultHttpClient()
.execute(request);
// 得到应答的字符串
retSrc = EntityUtils.toString(httpResponse.getEntity());
// 生成 JSON 对象
result = new JSONObject(retSrc);
} catch (Exception e) {
e.printStackTrace();
}
return result;//返回json对象
}
得到返回json对象并且解析
userRequest = getJsonRequest(Const.URL
+ "/sign_in.json", json);
int status=userRequest.getInt("status");//获取返回状态数字
JSONObject user = userRequest.getJSONObject("user");
int userId = user.getInt("id");//解析int格式
String nickName = user.getString("nickname");//解析string格式
返回格式是:
{
:status => 200,
:user => {
:id => 8,
:nickname => "逐风林羽",
}
}
还有数据类型:
JSONArray users = data.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
//然后再向上个例子一样解析user串
}
传输bitmap图片
public static JSONObject UpLoadRes(String url,String param,File bitmap ){
String retSrc = null;
JSONObject result = null;
//设置要访问的地址
HttpPost httpRequestHttpPost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8));
ContentBody contentBody = new FileBody(bitmap, "image/jpg");
try {
String newStr = new String(param.getBytes(), "UTF-8");
//添加内容
multipartEntity.addPart("email",new StringBody("eche.lau@gmail.com"));
multipartEntity.addPart("request",new StringBody(newStr, Charset.forName(HTTP.UTF_8)));
multipartEntity.addPart("res", contentBody);
//把要传输的内容放到请求里面
httpRequestHttpPost.setEntity(multipartEntity);
//创建客户端对象
HttpClient httpClient = new DefaultHttpClient();
//执行请求并得到返回结果
HttpResponse httpResponse = httpClient.execute(httpRequestHttpPost);
retSrc = EntityUtils.toString(httpResponse.getEntity());
// 生成 JSON 对象
result = new JSONObject(retSrc);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}