我想使用Java向一些服务发送post请求。请求必须包含一些参数,其中一个是多行字符串。我尝试了很多方法,但每次我最终将整个文本作为单行提交而没有换行符。有什么想法吗?
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;
}
我仅限于标准Java Api,因此不允许使用外部库。
答案 0 :(得分:1)
// ...
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
// ...
答案 1 :(得分:0)
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"));
}
}
输出:
富
杆
只需解码编码数据即可。 URLEncoder#encode(String s, "UTF-8")
将对保留集之外的任何字符进行百分比编码。见Percent encoding of character data.