使用HttpURLConnection发送UTF-8字符串 [英] Sending UTF-8 string using HttpURLConnection

查看:136
本文介绍了使用HttpURLConnection发送UTF-8字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经使用以下代码段发送和接收JSON字符串:

till now I've used the following code snippet in order to send and recieve JSON strings:

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字符,上面的代码也可以完美地工作,并且一切正常.

The code above worked perfect even if the json string contained UTF-8 chars, and everything worked fine.

由于多种原因,我不得不更改发送HTTP发布请求的方式,并使用HttpURLConnection代替apache的HttpClient.这是我的代码:

For several reasons I had to change the way I send HTTP post requests and use HttpURLConnection instead apache's HttpClient. Here's my code:

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时,我认为它确实起作用,因为我可以查看特殊字符.)

This code works well for normal English characters, but doesn't seem to support UTF-8 characters in the json string, since it fails each time. (when sending json to server, server crushes saying that utf8 cant decode a certain byte, but when recieving utf8 json from server I think it does work since I manage to view the special characters).

服务器完全没有变化,并且可以与以前的代码一起正常工作,因此问题是此新代码段中的100%.

Server didn't change at all and worked fine with previous code, so the problem is 100% on this new code snippet.

有什么想法如何解决json字符串发送问题,以便它支持UTF 8?谢谢

Any idea how to fix the json string sending so it would support UTF 8? Thanks

推荐答案

我认为问题出在这部分:

I think the problem is in this part:

DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(json);
outputStream.flush();
outputStream.close();

您需要将json编码为UTF-8,而不是这样做
并发送代表UTF-8编码的那些字节.

Instead of doing this you need to encode json as UTF-8
and send those bytes which represent the UTF-8 encoding.

尝试使用此:

Charset.forName("UTF-8").encode(json)

请参阅:

Charset.encode

一种更简单的方法是使用BufferedWriter包装一个
OutputStreamWriter. OutputStreamWriter知道自己的编码
因此它将为您完成工作(json字符串的编码工作).

An even simpler approach is to use e.g. a BufferedWriter wrapping an
OutputStreamWriter. The OutputStreamWriter knows about its own encoding
and so it will do the work for you (the encoding work of the json String).

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
bw.write(json);
bw.flush();
bw.close();

这篇关于使用HttpURLConnection发送UTF-8字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆