【发布时间】:2014-10-16 12:28:38
【问题描述】:
我尝试将图像(base64 编码)连同其他值一起上传到 PHP 网络服务器,它会获取这些信息并进行一些进一步的处理。
以下函数是执行请求的 AsyncTask 的一部分。
我通过手动连接不同的值来构建 postData。
JsonUrlLook 类帮助我找到发送数据的正确 URL。我验证过了。没错。
当我尝试执行创建的 HttpPost 时,我的响应为空。有人知道这是为什么吗?
private String getPostData(String arrayString, String base64Image, String boundary) {
String remoteMethod = "uploadPic";
String postData = "";
// Add remote method name
postData += "--" + boundary + "\r\n";
postData += "Content-Disposition: form-data; name=\"" + boundary + "[method]\"\r\n\r\n";
postData += remoteMethod;
postData += "--" + boundary + "\r\n";
postData += "Content-Disposition: form-data; name=\"" + boundary + "[params]\"\r\n\r\n";
postData += arrayString;
postData += "--" + boundary + "\r\n";
postData += "Content-Disposition: form-data; name=\"" + boundary + "\"\r\n\r\n";
postData += "filename=\"image.jpg\"\r\n\r\n";
postData += base64Image;
postData += "--" + boundary + "--";
return postData;
}
private String uploadPicture(String arrayString, String base64Image) {
String boundary = "tx_fpoemobile_pi2";
// Get post data
String postData = getPostData(arrayString, base64Image, boundary);
// Get webservice uri
JsonUrlLookup lookup = new JsonUrlLookup(context);
URL webserviceUrl = lookup.buildUrl(context.getResources().getString(R.string.page_uid_webservice));
URI webserviceUri = null;
try {
webserviceUri = new URI(webserviceUrl.toString());
} catch(Exception e) {
// TODO
}
// Build client and post
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(webserviceUri);
// Set header of post
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
httpPost.setHeader("Content-Length", String.valueOf(postData.length()));
// Set body
try {
httpPost.setEntity(new StringEntity(postData));
} catch (Exception e) {
// TODO
}
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO
} catch (IOException e) {
// TODO
}
return "uploadPictureSuccess";
}
【问题讨论】:
标签: android image http-post multipart