0

I have a web service and I want to invoke that with "application/x-www-form-urlencoded" content type. The request sometimes contains special characters such as + * - and .... The problem is that destination web service doesn't receive the request perfectly. It receives something like this: "////////////////w==" almost all characters are turned to / . What is the problem?

Here is my code:

        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();

The web service receives:

test=////////////////w==
Kian
  • 211
  • 1
  • 3
  • 17
  • https://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html – JB Nizet Jul 17 '18 at 12:23
  • That doesn't help. The encoded request is : "test=%21%40%23%24%25%5E%26*%28%29_%2B%2F-%2B", but the server receives this: "test=///////////+//++" – Kian Jul 17 '18 at 12:50
  • 2
    Then your server has a problem. I tested your code (with url encoding added) on https://postman-echo.com/post, and everything works as expected. – JB Nizet Jul 17 '18 at 13:13

1 Answers1

1

Use URLEncoder to encode the string before sending.

URLEncoder.encode(message, "UTF-8" );

In this case it will be

outputStreamWriter.write(URLEncoder.encode("test=/-+*=!@#$%^&*()_", "UTF-8" ));
Sahal
  • 278
  • 2
  • 10
  • That doesn't help. The encoded request is : "test=%21%40%23%24%25%5E%26*%28%29_%2B%2F-%2B", but the server receives this: "test=///////////+//++" – Kian Jul 17 '18 at 12:49
  • This post might help. https://stackoverflow.com/questions/40574892/how-to-send-post-request-with-x-www-form-urlencoded-body – Sahal Jul 17 '18 at 13:11