2011-12-20 1 views
2

を使用してJSONにバイト配列を送信する:アンドロイド:私はIDを含むオブジェクト(文字列)と画像(バイト[])を受け入れ、JSON POSTメソッドでJSONサーバ(WCF REST)を有するPOST

[DataContract(Name = "image")] 
public class CustomImage 
{ 
    [DataMember(Name = "id")] 
    public string Id { get; set; } 
    [DataMember(Name = "imagestream")] 
    public byte[] ImageStream { get; set; } 
} 

次のコードを使用してC#コンソールアプリケーションからサーバーにデータを送信することができました: `byte [] bytearray = null;

 Stream stream = File.OpenRead(@"c:\temp\snow.jpg"); 
     stream.Seek(0, SeekOrigin.Begin); 
     bytearray = new byte[stream.Length]; 
     int count = 0; 
     while (count < stream.Length) 
     { 
      bytearray[count++] = Convert.ToByte(stream.ReadByte()); 
     } 

     CustomImage image = new CustomImage {Id = "43"}; 
     image.ImageStream = bytearray; 
     WebClient Proxy1 = new WebClient(); 

     Proxy1.Headers["Content-type"] = "application/json"; 
     MemoryStream ms = new MemoryStream(); 
     DataContractJsonSerializer serializerToUpload = new DataContractJsonSerializer(typeof (CustomImage)); 
     serializerToUpload.WriteObject(ms, image); 
     byte[] data = Proxy1.UploadData("http://localhost:5465/MyService/file/post", "POST", ms.ToArray());` 

しかし、Androidアプリケーションではこれを動作させることができません。私は次のコードを使用しています: `public boolean UploadImage(String id、byte [] imageData)JSONException、UnsupportedEncodingExceptionをスローします。{ BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = getHttpClient();

HttpResponse response = null; 
    HttpPost httpost = null; 

    String url = String.format("file/post"); 
    url = String.format("%s/%s", API_ROOT, url); 

    httpost = new HttpPost(url); 

    //JSONArray jsonArray = new JSONArray();  
    //for(int i=0;i<imageData.length;i++) { 
    // jsonArray.put(imageData[i]); 
    //} 

    JSONObject data = new JSONObject(); 
    data.put("id", id); 
    data.put("imagestream", imageData); 
    data.put("imagestream", jsonArray); 


    StringEntity se = null; 
    se = new StringEntity(data.toString()); 

    httpost.setEntity(se); 

    response = null; 
    httpost.setHeader("Accept", "application/json"); 
    httpost.setHeader("Content-type", "application/json"); 

    try { 

     response = httpClient.execute(httpost, localContext); 
    } catch (ClientProtocolException e) { 
     // System.out.println("HTTPHelp : ClientProtocolException : " + 
     // e); 
    } catch (IOException e) { 
     // System.out.println("HTTPHelp : IOException : " + e); 
    } 

    if (response != null && response.getStatusLine() != null 
      && response.getStatusLine().getStatusCode() == 200) { 

     return true; 
    } 
    return false; 
} 

しかし、私は取得していますすべてがある: `リクエストボディは

直列化復元することができませんでした。名前空間 ''から要素imageStreamを終了します。見つかったテキスト '[B @ 406bb748'。

答えて

3

画像を確認してください。おそらく、それが送信される前にBase64でエンコードされている必要があります。

+0

こんにちは、画像をエンコードする方法Base64? –

+1

http://bit.ly/WQslsV – Kuffs

+0

私はそれを得ました。しかし、私はそのバイト[]の代わりにStringをポストする必要がありますか? –

関連する問題