2014-09-04 68 views
1

我有一個使用MultipartEntity內容類型將圖像和文本作爲HttpPost發送的方法。一切都很適合英文符號,但對於unicode符號(例如Cyrliics),它只發送???。所以,我想知道,如何正確地爲MultipartEntity設置UTF-8編碼,因爲我已經嘗試了幾個在SO上建議的解決方案,但沒有一個能夠工作。 這裏我已經:通過MultipartEntity發送Unicode字符

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(url); 

MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create(); 
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
mpEntity.setCharset(Consts.UTF_8); 

mpEntity.addPart("image", new FileBody(new File(attachmentUri), ContentType.APPLICATION_OCTET_STREAM)); 


ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8); 
StringBody stringBody = new StringBody(mMessage, contentType); 
mpEntity.addPart("message", stringBody); 

final HttpEntity fileBody = mpEntity.build(); 
httpPost.setEntity(fileBody); 

HttpResponse httpResponse = httpclient.execute(httpPost); 

UPD 我試圖用的InputStream按@Donaudampfschifffreizeitfahrt建議。現在我得到了 個字符。

InputStream stream = new ByteArrayInputStream(mMessage.getBytes(Charset.forName("UTF-8"))); 
mpEntity.addBinaryBody("message", stream); 

也試過:

mpEntity.addBinaryBody("message", mMessage.getBytes(Charset.forName("UTF-8"))); 
+1

您正在使用'默認字符集'進行IO操作,無論您是使用什麼操作。這是來自Sun的一個糟糕的設計,你必須**總是**使用OutputStreamReader/InputStreamWriter與指定的編碼,如果你處理寫/讀字符串。 – 2014-09-04 12:15:22

+0

@Donaudampfschifffreizeitfahrt您好!你能更具體一點,我怎麼能在我的問題的上下文中使用InputStreamWriter?示例將不勝感激。謝謝。 – mol 2014-09-04 12:34:55

+0

呵呵,應該是OutputStreamWriter和InputStreamReader。 httpclient必須具有Body類型接受Writer,但我現在沒有該庫。只需搜索這些類名稱即可。 – 2014-09-04 12:39:18

回答

0

爲了誰堅持這個問題的,我這是怎麼解決它:

我調查的Apache HTTP組件庫的源代碼,發現以下幾點:

org.apache.http.entity.mime.HttpMultipart::doWriteTo() 


case BROWSER_COMPATIBLE: 
    // Only write Content-Disposition 
    // Use content charset 

    final MinimalField cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION); 
    writeField(cd, this.charset, out); 
    final String filename = part.getBody().getFilename(); 
    if (filename != null) { 
     final MinimalField ct = part.getHeader().getField(MIME.CONTENT_TYPE); 
     writeField(ct, this.charset, out); 
    } 
    break; 

所以,好像它是某種類型的apache lib中的bug /功能,它只允許將Content-type標頭添加到MultipartEntity的一部分,如果該部分的文件名不爲空。所以我修改我的代碼爲:

Charset utf8 = Charset.forName("utf-8"); 
ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), utf8); 
ContentBody body = new ByteArrayBody(mMessage.getBytes(), contentType, "filename"); 
mpEntity.addPart("message", body); 

並且內容類型頭部出現在字符串部分,符號現在被正確編碼和解碼。

1

我解決它以不同的方式使用:

builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8")); 
1

可以在多實體

entity.addPart( 「數據」,新StringBody(數據,字符集使用以下行添加零件。的forName( 「UTF-8」)));

要求發送unicode。