Tomasz Dziurko
Tomasz Dziurko

Reputation: 1688

Send multiline String via HTTP Post in Java

I want to send post request to some service using Java. Requests must contain some parameters and one 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.

Upvotes: 2

Views: 7682

Answers (2)

Sahil Muthoo
Sahil Muthoo

Reputation: 12506

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.

Upvotes: 0

aalku
aalku

Reputation: 2878

// ...
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
// ...

Upvotes: 1

Related Questions