到目前为止,我一直使用以下代码片段来发送和接收JSON字符串:
static private String sendJson(String json,String url){
HttpClient httpClient = new DefaultHttpClient();
String responseString = "";
try {
HttpPost request = new HttpPost(url);
StringEntity params =new StringEntity(json, "UTF-8");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
}catch (Exception ex) {
ex.printStackTrace();
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseString;
}
即使JSON字符串包含UTF-8字符,上述代码仍能完美运行,一切都正常。
由于几个原因,我必须改变发送HTTP POST请求的方式,并使用HttpURLConnection而不是Apache的HttpClient。以下是我的代码:
static private String sendJson(String json,String url){
String responseString = "";
try {
URL m_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)m_url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("content-type", "application/json");
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(json);
outputStream.flush();
outputStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
responseString = sb.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseString;
}
这段代码对于普通的英文字符可以正常工作,但是似乎无法支持json字符串中的UTF-8字符,因为每次都会失败。(当向服务器发送json时,服务器会崩溃并说utf8无法解码某个字节,但是当从服务器接收utf8 json时,我认为它可以正常工作,因为我能够查看特殊字符)。
服务器完全没有改变,以前的代码也可以正常工作,所以问题100%是在这个新的代码片段上。
有什么办法可以修复json字符串发送,使其支持UTF 8?谢谢