【问题标题】:Uploading a Photo to Server via JSON with Android [closed]使用 Android 通过 JSON 将照片上传到服务器 [关闭]
【发布时间】:2012-03-19 19:42:55
【问题描述】:

我正在尝试将照片上传到我的服务器。但我对如何将多部分请求作为 JSON 提交感到困惑。这是我到目前为止的代码。

// Set up HTTP client.
HttpClient client = DefaultHttpClient();

// Multi-part content body.
MultipartEntity mpEntity = new MultipartEntity();
ContentBody content = new FileBody(source, "image/jpeg");
mpEntity.addPart("user[photo]", content);

// Put method.
HttpPut method = new HttpPut(url);
method.setHeader("Accept", "application/json");
method.setHeader("Content-type", "application/json");
method.setHeader("Accept-Encoding", "gzip"); 
method.setEntity(mpEntity);
response = client.execute(method);

// Result.
HttpEntity responseEntity = response.getEntity();

我从 Rails 服务器得到的错误是:

Error occurred while parsing request parameters.
Contents: [garbled data]

【问题讨论】:

    标签: android image file-upload


    【解决方案1】:

    首先,这根本不是 android 特定的。这属于与 HTTP 相关的问题。不过我会回答的。

    您不能使用 application/json 内容类型发送多部分 http 消息。您应该对您的消息使用适当的多部分内容类型。尽管在您的示例中您只传递了一个部分,但从技术上讲,不需要多部分。但是,这取决于 Rails 服务器期望的请求内容。

    【讨论】:

    • 弗拉基米尔。我想出了一个真正让它发挥作用的方法。你说得对,我无法为application/json 设置标题。但我可以在 URL 级别设置它,Rails 服务器会接受它。我会在下面发布一个正确的答案。
    【解决方案2】:

    这适用于 Rails 服务器。

    // Target URL.
    // Add '.json' to end of the URL. This will make Rails
    // accept the request as JSON but yet allow the multi-part content
    // encoding below.
    String url = "http://blahblah.com/users/123.json"
    
    // Set up HTTP client.
    HttpClient client = DefaultHttpClient();
    
    // Multi-part content body.
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody content = new FileBody(source, "image/jpeg");
    mpEntity.addPart("user[photo]", content);
    
    // Put method.
    HttpPut method = new HttpPut(url);
    method.setEntity(mpEntity);
    response = client.execute(method);
    
    // Result.
    HttpEntity responseEntity = response.getEntity();
    

    有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多