HTTPConnectionURL in UTF-8 for Webservice POST



我正在为一个我无法控制的Web服务创建一个客户端。我正在尝试开机自检。这是我的代码。

        String generatedUrl = generateURL(); //Logic that creates the whole url
        logger.debug("URL = "+generatedUrl);
        StringBuffer response = new StringBuffer();
        HttpURLConnection connection = null;
        URL url;
        try {
            url = new URL(generatedUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String inputLine;

            while((inputLine = in.readLine()) != null){
                response.append(inputLine);
            }
            in.close();
            logger.debug("RESPONSE = "+response.toString());
        } catch (Exception e) {
            logger.error("Error = "+e);
        }   
        return response.toString();

问题是当我发送日语字符时。URL 包含正确的字符,但在 Web 服务端,只收到一堆奇怪的符号。如果我使用浏览器点击生成的 URL,它就可以正常工作。似乎我无法让我的 POST 以 UTF-8 格式通过。有什么想法吗?

我只需要在查询中出现问题的部分(例如名称)上使用 URLEncoder.encode() 方法,而不是对整个查询进行编码。所以,它最终看起来像这样

url = .... + URLEncoder.encode(name, "UTF-8) + ...

最新更新