java向某url发送一条post请求,并输出返回值字符串
时间: 2024-10-12 22:11:24 浏览: 29
在Java中,你可以使用HttpURLConnection或者第三方库如Apache HttpClient或者OkHttp来发送POST请求并获取响应。这里我们以HttpURLConnection为例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
private static final String POST_URL = "http://example.com/api/endpoint"; // 替换为你实际的URL
public static void main(String[] args) throws Exception {
URL url = new URL(POST_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置POST参数,例如这里是JSON格式
String postData = "{\"key\":\"value\"}";
byte[] bytes = postData.getBytes("UTF-8");
connection.setDoOutput(true);
connection.getOutputStream().write(bytes);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应字符串
System.out.println("Response: " + response.toString());
} else {
System.out.println("Failed to send POST request. Response code: " + responseCode);
}
connection.disconnect();
}
}
```
这段代码首先创建一个URL对象,然后通过HttpURLConnection对象连接到该URL并发起POST请求。如果HTTP状态码为200(成功),它将读取并打印出响应的内容。
阅读全文