【问题标题】:Send Image in Json : 400 Bad request在 Json 中发送图像:400 错误请求
【发布时间】:2013-08-15 14:25:46
【问题描述】:

我正在尝试从我的 android 将带有一类数据的图像发送到 IIS web 服务。 (C#)

问题是我得到400 Bad request

图像被编码为Base64。然后与其余的类元素一起放入json

我的猜测是 Base64 在 Json 中无效。所以服务器不理解它。 如果我将字符串设置为"",则帖子会被接受。

所以问题是,如何使我的 Base64Json 数组中有效?(我尝试了 URL.Encode,但没有成功)。

或者你应该如何将图像从android发送到webservice?

 Gson gson = new Gson();

 String json = gson.toJson(record);  // record has param { String base64Photo }

【问题讨论】:

    标签: c# android json web-services base64


    【解决方案1】:

    图片有多大?我很确定您已经超过了 IIS Json 大小限制(默认值几乎是 4 MB)。

    查看http://geekswithblogs.net/frankw/archive/2008/08/05/how-to-configure-maxjsonlength-in-asp.net-ajax-applications.aspxhttp://www.webtrenches.com/post.cfm/iis7-file-upload-size-limits

    祝你好运!

    【讨论】:

    • 值得考虑,但我只是拍了一张照片,它只有 81.5KB。因为它是 Jpg 格式,而不是位图。无论如何添加了建议的代码,仍然是同样的问题。
    • 通过一些额外的大小限制更改,包括字符串和缓冲区大小,它确实解决了我的问题。我在以前的项目中已经做过的事情。那谢谢啦! <binding name="rest" maxBufferSize="1024000" maxReceivedMessageSize="1024000" crossDomainScriptAccessEnabled="true" > <readerQuotas maxDepth="32" maxStringContentLength="8000192" maxArrayLength="104857600" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> </binding>
    【解决方案2】:

    老实说,我从未将图像从 Android 上传到 IIS 网络服务,但在其他所有情况下,我一直只使用File。创建文件并将其上传为MultipartEntity 很容易。另外,您不必同时使用Base64,这很好,因为它为您节省了使用Base64 所增加的大约33% 的开销。

    private File createFileFromBm(Bitmap pic){
        File f = new File(context.getCacheDir(), "image");
    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        pic.compress(CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();
    
        try{
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(data);
            fos.close();
        } catch (IOException e){
            Log.e(TAG, e.toString());
        }
    
        return f;
    }
    

    这是创建MultipartEntity的方法

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE;              
    entity.addPart("photo", new FileBody(file, "image/jpeg"));
    httpPost.setEntity(entity);
    return httpClient.execute(httpPost, responseHandler);
    

    我在这里使用了HttpPostBasicResponseHandler 来接收来自服务器的JSON 输出进行处理,但您可以做任何您喜欢的事情。

    【讨论】:

    • 好的,如果我的课程中有一个 FileBody,服务器将如何表示它?只使用File 类型参数?
    • 如果可以的话。当我使用 PHP 执行此操作时,只有一个传入的 File 数组接受这种输入。我猜想在 IIS 中存在,但我真的不知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2020-05-14
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多