【问题标题】:Send image from Android to WCF using JSON and MultipartEntity使用 JSON 和 MultipartEntity 将图像从 Android 发送到 WCF
【发布时间】:2012-09-26 00:08:40
【问题描述】:

由于我的所有其他消息都将是 JSON,我想我会将我的 Android 解决方案转换为使用 JSON 多部分消息从相机拍摄的图像发送到 WCF 服务。我想我有发送工作,但不知道如何反序列化。我不使用 base64 编码的原因是我希望 android 2.1 工作而 base64 编码不起作用(至少这是我读过的,我发现唯一的“hack”只适用于小文件)。

所以在android中我尝试发送图片:

public void upload() throws Exception {
    //Url of the server
    String url = "http://192.168.0.10:8000/service/UploadImage";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity();
    //Path of the file to be uploaded
    String filepath = path;
    File file = new File(filepath);
    ContentBody cbFile = new FileBody(file, "image/jpeg");     

    //Add the data to the multipart entity
    mpEntity.addPart("image", cbFile);
    post.setEntity(mpEntity);
    //Execute the post request
    HttpResponse response1 = client.execute(post);
    //Get the response from the server
    HttpEntity resEntity = response1.getEntity();
    String Response=EntityUtils.toString(resEntity);
    Log.d("Response:", Response);

    client.getConnectionManager().shutdown();
}

wcf(就像我使用来自 android 的 httpurlconnect 和 outputstream 发送时一样)代码。那时它正在工作:D:

public string UploadImage(Stream image)
    {
        var buf = new byte[1024];
        var path = Path.Combine(@"c:\tempdirectory\", "test.jpg");
        int len = 0;
        using (var fs = File.Create(path))
        {
            while ((len = image.Read(buf, 0, buf.Length)) > 0)
            {
                fs.Write(buf, 0, len);
            }
        }
        return "hej";
    }  

wcf 的接口 [运营合同] [网络调用( 方法 = "POST", UriTemplate = "/UploadImage", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string UploadImage(流图);

如果重要的话,运行 wcf 的控制台应用程序

   static void Main(string[] args)
    {
        string baseAddress = "http://192.168.0.10:8000/Service";
        ServiceHost host = new ServiceHost(typeof(ImageUploadService), new Uri(baseAddress));
        WebHttpBinding binding = new WebHttpBinding();
        binding.MaxReceivedMessageSize = 4194304;

        host.AddServiceEndpoint(typeof(IImageUploadService),binding , "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");
        Console.ReadKey(true);
    }

那么现在的问题是,我如何解析传入的 JSON 流?有没有更好的方法?

注意:我尝试设置提琴手,但 3 小时后甚至无法读取流量,我放弃了。

有什么好的方法可以实际调试这段代码吗?

如果我将流转换为字节数组并将其保存到文件中,忘记包含结果:

--IZZI8NmDZ-Id7DWP5z0nuPPZspVAGglcfEY9
    Content-Disposition: form-data; name="image"; filename="mypicture.jpg"
    Content-Type: image/jpeg
    Content-Transfer-Encoding: binary

   ÿØÿá°Exif and other funny letters of cause :D ending with
   --IZZI8NmDZ-Id7DWP5z0nuPPZspVAGglcfEY9--

通过一些新代码我可以设法得到这个

--crdEqve1GThGGKugB3On0tGNy5h2u746
Content-Disposition: form-data; name="entity"

{"filename":"mypicture.jpg"}
--crdEqve1GThGGKugB3On0tGNy5h2u746
Content-Disposition: form-data; name="file"; filename="mypicture.jpg"
Content-Type: application/octet-stream

ÿØÿá´Exif and the whole image here ...

新的更新例程如下所示:

public void uploadFile() {
         String filepath = path;
            File file = new File(filepath);
        HttpClient httpClient = new DefaultHttpClient();

        HttpPost postRequest = new HttpPost("http://192.168.0.10:8000/service/UploadImage");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // Indicate that this information comes in parts (text and file)
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        try {

            //Create a JSON object to be used in the StringBody
            JSONObject jsonObj = new JSONObject();

            //Add some values
            jsonObj.put("filename", file.getName());

            //Add the JSON "part"
            reqEntity.addPart("entity", new StringBody(jsonObj.toString()));
        }
        catch (JSONException e) {
            Log.v("App", e.getMessage());
        }
        catch (UnsupportedEncodingException e) {
            Log.v("App", e.getMessage());
        }

        FileBody fileBody = new FileBody(file);//, "application/octet-stream");
            reqEntity.addPart("file", fileBody);

            try {
                postRequest.setEntity(reqEntity);

                 //Execute the request "POST"
            HttpResponse httpResp = httpClient.execute(postRequest);

            //Check the status code, in this case "created"
            if(((HttpResponse) httpResp).getStatusLine().getStatusCode() == HttpStatus.SC_CREATED){
                Log.v("App","Created");
            }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

我仍然需要一种方法来分离流的不同部分,以便我可以划分 json 消息部分(如果我需要这些部分),然后将图像的字节数组作为单独的部分进行存储。我想我可以跳过 json 并返回到我原来的只是发送图像的字节数组,但是无论如何我都需要能够处理 JSON 消息。

感谢到目前为止的 cmets。

【问题讨论】:

    标签: c# android json wcf


    【解决方案1】:

    我的第一个想法是它不是 JSON 流。它可能是一个字节流。此外,如果您的图像大于 1024 字节,您将无限读取和写入前 1024 字节。您应该有一个偏移量变量来跟踪您已阅读的内容并在此之后开始阅读。

    【讨论】:

    • 它可能是一个字节流,我在这方面的知识非常新:D。但是,它确实读取每个块 1024 字节并将其输出到文件。我已经添加了该文件的一部分,大小几乎是 2MB,这是正确的。
    • 绝对是字节流,而不是文本。查看来自微软的this 示例代码,了解如何使用 Stream.read()
    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多