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

Url 传json 数据

2016-05-13 16:37 323 查看
App 上传图片到服务器

以前是通过base64 把byte[] 转成string ,服务器转成bye[] 转 字节流写到文件里,但是发现速度太慢!

决定让ios 模仿html表单 用multipart/form-data 编码形式提交图片,用common-fileupload 来获取文件

下面是我搜的的资料链接
http://www.devdiv.com/iOS_iPhone-nsmutableurlrequest_multipart_form_data_post_-thread-200308-1-1.html http://www.jianshu.com/p/a0e3c77d3164 http://thierry-xing.iteye.com/blog/2069032
个人觉得这是可行的方式,但是ios一直没有实现,这种方式放弃

后来ios 找了一种方式,设置content-type image/jpg 图片放在请求体中,但我想不明白,这种方式可以,上面的方式原理差不多,为毛不能实现。

参数解析 通过是否有dataJson参数来判断是否需要上传图片

protected MRequest parseRequest(HttpServletRequest request) {
MRequest req = null;
String dataJson = request.getParameter("dataJson");
if (null == dataJson) {
InputStream in = null;
BufferedInputStream buf = null;
try {
StringBuffer info = new StringBuffer();
in = request.getInputStream();
buf = new BufferedInputStream(in);
int len = request.getContentLength();
if (len > 0) {
byte[] buffer = new byte[len];
int iRead;
while ((iRead = buf.read(buffer)) != -1) {
info.append(new String(buffer, 0, iRead, "UTF-8"));
}
req = JacksonUtil.getInstance().readValue(info.toString(),
new TypeReference<MRequest>() {
});
}
} catch (Exception e) {
logger.error("parseRequest(HttpServletRequest)", e);
e.printStackTrace();
} finally {
try {
buf.close();
in.close();
} catch (IOException e) {
logger.error("parseRequest(HttpServletRequest)", e);
e.printStackTrace();
}
}
} else {
String fileName = imgUpload(request);
try {
req = JacksonUtil.getInstance().readValue(dataJson,
new TypeReference<MRequest>() {
});
if (!StringUtils.isBlank(fileName)) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) req
.getData();
map.put("image", fileName);
req.setData(map);
}
} catch (Exception e) {
logger.error("parseRequest(HttpServletRequest)", e);
e.printStackTrace();
}

}

return req;
}
dataJson存放原来的json 参数 ,由于参数量不大,拼接在url后面

json有特殊字符 ,需要URLEncoder 编码

public static void main(String[] args) throws ParseException, IOException {
JSONObject object = new JSONObject();
JSONObject object1 = new JSONObject();
object.put("os", "ios");
object.put("cmd", 107);
object.put("ver", "1_0");
object.put("data", object1);
String s = object.toString();
FileEntity fe = new FileEntity(new File("D:/we/1.jpg"),
ContentType.create("image/jpg"));
String url = "http://192.168.66.117:8080/wdculture-mobile/mobile/webservice?dataJson="
+ URLEncoder.encode(s, "UTF-8");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(fe);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
log.info(EntityUtils.toString(entity, "UTF-8"));
httpPost.abort();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: