在Java中使用HttpURLConnection发送特殊字符

时间:2018-07-17 12:13:16

标签: java httpurlconnection

我有一个Web服务,我想使用“ application / x-www-form-urlencoded”内容类型来调用它。该请求有时包含特殊字符,例如+ *-和...。问题是目标Web服务无法完美接收该请求。它收到这样的消息:“ ////////////// w ==”几乎所有字符都变成/。有什么问题吗?

这是我的代码:

        URL url = new URL("a-web-service-url");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
        outputStreamWriter.write("test=/-+*=!@#$%^&*()_");
        outputStreamWriter.flush();
        InputStream inputStream = httpURLConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        StringBuilder stringBuilder;
        String line;
        for (stringBuilder = new StringBuilder(); (line = bufferedReader.readLine()) != null; stringBuilder = stringBuilder.append(line)) {
            ;
        }

        bufferedReader.close();
        httpURLConnection.disconnect();
        String response = stringBuilder.toString().trim();

Web服务收到:

test=////////////////w==

1 个答案:

答案 0 :(得分:1)

在发送之前使用URLEncoder对字符串进行编码。

outputStreamWriter.write(URLEncoder.encode("test=/-+*=!@#$%^&*()_", "UTF-8" ));

在这种情况下将是

<a>