I want to send post request to some service using Java. Requests must contain some parameters and one 开发者_C百科of them is multiline String. I tried many ways but everytime I end up with whole text submitted as single line without newline characters. Any ideas?
URL url = new URL("http://example.com/create");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String data = "param1=value&string=" + convertNewLineCharacters(text);
writer.write(data);
writer.flush();
// (...)
private String convertNewLineCharacters(String text) throws Exception {
String encodedString = URLEncoder.encode(text, "UTF-8");
encodedString = encodedString.replaceAll("%0A", "\r\n");
return encodedString;
}
I am limited to standard Java Api, so no external libraries are allowed.
// ...
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" ); // not sure it is important
// ...
writer.write(URLEncoder.encode(data, "UTF-8")); // urlencode the whole string and do not edit it
// ...
package com.foo;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class Foobar {
public static void main(String...args) throws UnsupportedEncodingException {
String text = URLEncoder.encode("Foo\nBar", "UTF-8");
System.out.println(URLDecoder.decode(text, "UTF-8"));
}
}
Output:
Foo
Bar
Just decode the encoded data. URLEncoder#encode(String s, "UTF-8")
will percent encode any characters outside of the reserved set. See Percent encoding of character data.
精彩评论