1

I need to send data to another system in a Java aplication via HTTP POST method. Using the Apache HttpClient library is not an option.

I create a URL, httpconection without problems. But when sending special character like Spanish Ñ, the system complains it is receiving Ñ instead of Ñ.

I've read many post, but I don't understand some things:

  • When doing a POST connection, and writing to the connection object, is it mandatory to do the URLEncode.encode(data,encoding) to the data being sent?

  • When sending the data, in some examples I have seen they use the conn.writeBytes(strData), and in other I have seen conn.write(strData.getBytes(encoding)). Which one is it better? Is it related of using the encode?

Update:

The current code:

URL url = new URL(URLstr);

conn1 = (HttpsURLConnection) url.openConnection();
conn1.setRequestMethod("POST");
conn1.setDoOutput(true);

DataOutputStream wr = new DataOutputStream(conn1.getOutputStream());
wr.writeBytes(strToSend);//data sent
wr.flush();
wr.close();

(later I get the response)

strToSend has been previously URLENCODE.encode(,"UTF-8") I still don't know if I must use urlencode in my code and/or setRequestProperty("Contentype","application/x-www-formurlencode"); Or if I must use .write(strToSend.getByte(??) Any ideas are welcome. I am testing also the real server (I dont know very much about it)

Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100
Lewis B
  • 59
  • 1
  • 8
  • you should ALWAYS use explicit encoding, otherwise your app will not work on every platform. Java uses UTF-16 for strings which is fine in many cases -- if you want to be ABSOLUTELY on the safe side you could switch to UTF-8. – specializt Nov 03 '15 at 10:20
  • can you show your code, where you create the post-request? Are you sure, your server is actually accepting utf-8? – JohnnyAW Nov 03 '15 at 10:21
  • 1
    @specializt: "Java uses UTF-16 for strings " Maybe internally. When you write bytes from Java and don't specify an encoding, it uses the OS default encoding, which is rather unpredicatable. As you say, ALWAYS use an explicit encoding. – Thilo Nov 03 '15 at 10:26
  • Re: UrlEncode: If you need that or not depends on what the server expects. These days, people like to POST raw data (like JSON strings) instead of form-encoded or url-encoded stuff. – Thilo Nov 03 '15 at 10:27
  • theres nothing "internal" about official documentation : http://stackoverflow.com/a/9699165/351861 – specializt Nov 03 '15 at 10:27
  • 1
    @specializt: Exactly. That is the internal representation. Not what you get from, say, `strData.getBytes()` – Thilo Nov 03 '15 at 10:29

0 Answers0