gpt4 book ai didi

android - 使用 Http Post 发送图像

转载 作者:IT老高 更新时间:2023-10-28 13:00:04 26 4
gpt4 key购买 nike

我想使用 Http Post 将图像从 android 客户端发送到 Django 服务器。图片是从图库中选择的。目前,我正在使用列表值名称 Pairs 将必要的数据发送到服务器并以 JSON 格式接收来自 Django 的响应。可以对图像使用相同的方法(在 JSON 响应中嵌入图像的 url)吗?

另外,哪种方法更好:远程访问图像而不从服务器下载它们或将它们下载并存储在位图数组中并在本地使用它们?图片数量少(<10)且尺寸小(50*50 dip)。

任何解决这些问题的教程将不胜感激。

编辑:从图库中选择的图像在缩放到所需大小后发送到服务器。

最佳答案

我假设您知道要上传的图片的路径和文件名。使用 image 作为键名,将此字符串添加到您的 NameValuePair

可以使用 HttpComponents libraries 发送图像.下载最新的 HttpClient (当前为 4.0.1 ) 二进制文件和依赖包并将 apache-mime4j-0.6.jarhttpmime-4.0.1.jar 复制到你的项目并添加将它们添加到您的 Java 构建路径中。

您需要将以下导入添加到您的类中。

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

现在您可以创建一个 MultipartEntity 来将图像附加到您的 POST 请求中。以下代码显示了如何执行此操作的示例:

public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new 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();
}
}

我希望这对您有所帮助。

关于android - 使用 Http Post 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2935946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com