Java Http(application/x-www-form-urlencoded)post请求方式代码示例
时间: 2023-11-08 16:54:33 浏览: 99
好的,以下是Java Http的application/x-www-form-urlencoded的post请求方式的代码示例:
```
import java.net.*;
import java.io.*;
public class HttpPostRequest {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置post请求方式
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置post请求参数
String urlParameters = "param1=value1¶m2=value2¶m3=value3";
// 发起post请求
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(urlParameters.getBytes());
os.flush();
os.close();
// 获取响应内容
int responseCode = con.getResponseCode();
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.toString());
}
}
```
希望对您有所帮助!
阅读全文