您的位置:首页 > Web前端 > JavaScript

使用xutils发送POST请求,携带json和图片二进制文件数据获取服务器端返回json数据

2014-09-02 17:42 1361 查看
接口文档:

换头像
接口 user/change_avatar

发送数据
HTTP Post body(一共2对KEY-VALUE):
json={"uid":"1","sid":"0123456789ABCDEF0123456789ABCDEF","ver":"1","request":{}}
file=图片二进制文件数据

返回数据
{"ret":0,"response":{
"status":1,
"url":"http://192.168.1.200:8088/thumb.php?src=984340199_1667541218_1540991412.jpg&t=a&w=112&h=112"
}
}

遇到的问题:
首先在封装二进制请求体参数时,传递参数不足,导致服务器端不识别POST请求。


HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams();
params.addBodyParameter("json", json);
for (int i = 0; i < files.size(); i++) {
if (files.get(i) != null) {
try {
params.addBodyParameter("file"+i, new FileInputStream(
files.get(i)), files.get(i).length(), files.get(i)
.getName(), "application/octet-stream");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


  params.addBodyParameter(key, stream, length, fileName, mimeType);

然后在发送POST请求时,使用的是异步方法,导致不能返回服务器返回的值。


String s = null;
try {
// 同步方法,获取服务器端返回的流
ResponseStream responseStream = http.sendSync(HttpMethod.POST, url,
params);
s = responseStream.readString();
} catch (Exception e) {
e.printStackTrace();
}
return s;


  ResponseStream responseStream = http.sendSync(method, url, params);

下面附上发送POST请求的完整代码:


/**
* 发送POST请求,携带json和多个文件参数得到服务器返回的结果(json格式),必须要开启子线程调用。否则得不到数据。
*
* @param url 请求地址
* @param json 请求体中封装的json字符串
* @param List<File> 上传多个文件
* @return String 服务器返回的结果
*/
public static String sendPost(String url, String json, List<File> files) {
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams();
params.addBodyParameter("json", json);
if (files.size() == 1) {
try {
params.addBodyParameter("file",
new FileInputStream(files.get(0)), files.get(0)
.length(), files.get(0).getName(),
"application/octet-stream");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
for (int i = 0; i < files.size(); i++) {
if (files.get(i) != null) {
try {
params.addBodyParameter("file" + i,
new FileInputStream(files.get(i)), files.get(i)
.length(), files.get(i).getName(),
"application/octet-stream");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
String s = null;
try {
// 同步方法,获取服务器端返回的流
ResponseStream responseStream = http.sendSync(HttpMethod.POST, url,
params);
s = responseStream.readString();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐