Android 使用 Http Post 发送图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2935946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:58:00  来源:igfitidea点击:

Sending images using Http Post

androiddjangohttp

提问by Primal Pappachan

I want to send an image from the android client to the Django server using Http Post. The image is chosen from the gallery. At present, I am using list value name Pairs to send the necessary data to the server and receiving responses from Django in JSON. Can the same approach be used for images (with urls for images embedded in JSON responses)?

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

Also, which is a better method: accessing images remotely without downloading them from the server or downloading and storing them in a Bitmap array and using them locally? The images are few in number (<10) and small in size (50*50 dip).

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

Any tutorial to tackle these problems would be much appreciated.

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

Edit: The images chosen from the gallery are sent to the server after scaling it to required size.

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

回答by Piro

I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePairusing imageas the key-name.

我将假设您知道要上传的图像的路径和文件名。将此字符串添加到您的NameValuePairusing 中image作为键名。

Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jarand httpmime-4.0.1.jarto your project and add them to your Java build path.

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

You will need to add the following imports to your class.

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

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;

Now you can create a MultipartEntityto attach an image to your POST request. The following code shows an example of how to do this:

现在您可以创建一个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();
    }
}

I hope this helps you a bit in the right direction.

我希望这可以帮助您朝着正确的方向前进。

回答by AZ_

Version 4.3.5 Updated Code

版本 4.3.5 更新代码

  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar
  • httpclient-4.3.5.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.5.jar

Since MultipartEntityhas been deprecated. Please see the code below.

由于MultipartEntity已被弃用。请看下面的代码。

String responseBody = "failure";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

String url = WWPApi.URL_USERS;
Map<String, String> map = new HashMap<String, String>();
map.put("user_id", String.valueOf(userId));
map.put("action", "update");
url = addQueryParams(map, url);

HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);

if (career != null)
    builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (gender != null)
    builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (username != null)
    builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (email != null)
    builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (password != null)
    builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (country != null)
    builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
if (file != null)
    builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());

post.setEntity(builder.build());

try {
    responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
//  System.out.println("Response from Server ==> " + responseBody);

    JSONObject object = new JSONObject(responseBody);
    Boolean success = object.optBoolean("success");
    String message = object.optString("error");

    if (!success) {
        responseBody = message;
    } else {
        responseBody = "success";
    }

} catch (Exception e) {
    e.printStackTrace();
} finally {
    client.getConnectionManager().shutdown();
}

回答by vonox7

The loopjlibrary can be used straight-forward for this purpose:

循环J库可用于直接的用于此目的:

SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));

client.post("http://example.com", params, new TextHttpResponseHandler() {
  @Override
  public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    // error handling
  }

  @Override
  public void onSuccess(int statusCode, Header[] headers, String responseString) {
    // success
  }
});

http://loopj.com/

http://loopj.com/

回答by DavidC

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

我在尝试使用 httpclient-4.3.5.jar、httpcore-4.3.2.jar、httpmime-4.3.5.jar 将图像从 Android 客户端发布到 servlet 时遇到了很多困难。我总是遇到运行时错误。我发现基本上你不能在 Android 上使用这些 jars,因为谷歌在 Android 中使用旧版本的 HttpClient。解释在这里http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html。您需要从android http-client library获取 httpclientandroidlib-1.2.1 jar 。然后将您的导入从 or.apache.http.client 更改为 ch.boye.httpclientandroidlib。希望这可以帮助。

回答by Dylan McClung

I usually do this in the thread handling the json response:

我通常在处理 json 响应的线程中执行此操作:

try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.

如果需要对图像进行转换,则需要创建 Drawable 而不是 Bitmap。