javaurlencode编码post传参
时间: 2023-11-11 22:51:33 浏览: 85
Java中可以使用URLEncoder类进行URL编码。在进行POST请求时,需要将参数进行URL编码后才能进行传输。以下是一个例子:
```
import java.net.URLEncoder;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostExample {
public static void main(String[] args) throws Exception {
String urlParameters = "param1=" + URLEncoder.encode("value1", "UTF-8") +
"¶m2=" + URLEncoder.encode("value2", "UTF-8");
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}
}
```
在上面的例子中,我们将参数编码为URL编码格式,并在POST请求中进行传输。注意,我们需要将参数拼接成一个字符串,并在每个参数值之前加上参数名和等号,使用“&”符号将多个参数连接起来。
当然,具体要根据自己的实际需求来选择合适的URL编码方式。
阅读全文