Java中通过HTTP Post发送多行字符串
我想使用 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,因此不允许使用外部库。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出:
福
Bar
只需解码编码数据即可。
URLEncoder#encode(String s, "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.