请找到我的内联commnets,所有这一切都发生在一个按钮点击中。
我的问题是:
有没有更好的(或安卓风格的)方法来做同样的事情?
在异步任务或服务中触发 Web 服务调用的理想方法,因此在 HTTP 触发并获得响应之前,您的 UI 线程不会被阻塞。
检索图形内容并将其发布到基于 REST 的 Web 服务的首选方法是什么?
当您尝试从后端检索图形内容时,它通常是 base64。参考这个例子:http ://androidtrainningcenter.blogspot.in/2012/03/how-to-convert-string-to-bitmap-and.html
对于将图形发布到服务器,我假设您知道要上传的图像的路径和文件名。使用 image 作为键名将此字符串添加到您的 NameValuePair。
可以使用 HttpComponents 库来发送图像。下载最新的 HttpClient(当前为 4.0.1)二进制文件和依赖包并将 apache-mime4j-0.6.jar 和 httpmime-4.0.1.jar 复制到您的项目中,并将它们添加到您的 Java 构建路径中。
您需要将以下导入添加到您的类中。
导入 org.apache.http.entity.mime.HttpMultipartMode;导入 org.apache.http.entity.mime.MultipartEntity;导入 org.apache.http.entity.mime.content.FileBody;导入 org.apache.http.entity.mime.content.StringBody;现在您可以创建一个 MultipartEntity 来将图像附加到您的 POST 请求中。以下代码显示了如何执行此操作的示例:
public void post(String url, List nameValuePairs) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = 新的 HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
希望这可以帮助!