简体   繁体   English

通过Java中的HTTP Post发送多行字符串

[英]Send multiline String via HTTP Post in Java

I want to send post request to some service using Java. 我想使用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. 我仅限于标准Java Api,因此不允许使用任何外部库。

// ...
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 输出:Foo
Bar 酒吧

Just decode the encoded data. 只需解码编码的数据。 URLEncoder#encode(String s, "UTF-8") will percent encode any characters outside of the reserved set. URLEncoder#encode(String s, "UTF-8")将对保留集以外的任何字符进行百分比编码。 See Percent encoding of character data. 请参阅字符数据的百分比编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM