如何在异步任务的http post请求中发送unicode字符



我看到了这篇文章如何在Android上的HttpPost中发送unicode字符,但我通常在AsyncTask类中以这种方式进行请求。我的日志也在urlParameters中打印本地语言,但服务器没有返回任何结果,因为它非常适合英语字符串:

@Override
protected String doInBackground(String... URLs) {
    StringBuffer response = new StringBuffer();
    try {
        URL obj = new URL(URLs[0]);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // add request header
        con.setRequestMethod("POST");
        if (URLs[0].equals(URLHelper.get_preleases)) {
            urlCall = 1;
        } else
            urlCall = 2;
        // String urlParameters = "longitude=" + longitude + "&latitude="+latitude;
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response.toString();
}

有没有一种方法可以设置字符集UTF-8来请求以这种方式编码的参数?

字符串url参数="经度="+经度+"&纬度="+纬度;

您需要对要注入到application/x-www-form-urlencoded上下文中的组件进行URL编码。(即使除了非ASCII字符之外,与号等字符也会中断。)

指定您在该调用中用于请求的字符串到字节的编码,例如:

String urlParameters = "longitude=" + URLEncoder.encode(longitude, "UTF-8")...

DataOutputStream wr=新数据输出流(con.getOutputStream());

DataOutputStream用于向下流发送类似Java类型的结构的二进制数据。它不会为您提供编写HTTP请求体所需的任何内容。也许你的意思是OutputStreamWriter

但既然你已经在内存中有了字符串,你可以简单地做:

con.getOutputStream().write(urlParameters.getBytes("UTF-8"))

(请注意,这里的UTF-8有些多余。因为您已经将URL将所有非ASCII字符编码到%xx转义中,所以UTF-8编码不会有任何内容。但是,通常情况下,指定特定编码比省略它并恢复到不可靠的系统默认编码要好。)

新的InputStreamReader(con.getInputStream())

也省略了编码并恢复到默认编码,这可能不是响应的编码。因此,您可能会发现非ASCII字符在响应中也被错误读取。

最新更新