java发送post请求带参数
时间: 2023-06-23 17:49:43 浏览: 119
用java写post请求(添加post参数)
好的,下面是Java发送POST请求带参数的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String name = "John";
int age = 30;
String data = "name=" + URLEncoder.encode(name, "UTF-8") + "&age=" + age;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response : " + response.toString());
}
}
```
这段代码会向指定的URL发送一个POST请求,请求的参数是name和age,然后把服务器返回的响应打印出来。其中,name需要使用URLEncoder.encode()方法进行编码,以避免URL中的特殊字符引起问题。
阅读全文