使用java语言编写一个httppost请求示例
时间: 2023-06-02 13:05:34 浏览: 104
java使用httpclient发送post请求示例
3星 · 编辑精心推荐
好的,以下是一个使用 Java 语言编写的 HttpPost 请求示例:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
Map<String, String> params = new HashMap<>();
params.put("username", "myusername");
params.put("password", "mypassword");
String response = sendHttpPost(url, params);
System.out.println(response);
}
public static String sendHttpPost(String url, Map<String, String> params) throws IOException {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// generate url encoded parameters
String urlParameters = getURLEncodedParameters(params);
// Send post request
con.setDoOutput(true);
con.getOutputStream().write(urlParameters.getBytes("UTF-8"));
int responseCode = con.getResponseCode();
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
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();
return response.toString();
}
private static String getURLEncodedParameters(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
return result.toString().substring(0, result.length() - 1);
}
}
```
这段代码使用了 `java.net.HttpURLConnection` 类来发送 HTTP POST 请求,并将请求参数编码为 URL 编码形式。您可以根据需要修改 URL 和参数。
阅读全文