java如何向python发送http请求病获取python的返回结果
时间: 2023-10-18 18:28:29 浏览: 48
Java可以使用Apache HttpComponents或者Java原生的URLConnection类来向Python发送HTTP请求,并获取Python的返回结果。下面是使用HttpComponents发送POST请求的示例代码:
```
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
httpPost.setHeader("Content-Type", "application/json");
String requestBody = "{\"key\":\"value\"}";
StringEntity entity = new StringEntity(requestBody);
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) {
String responseString = EntityUtils.toString(responseEntity);
System.out.println(responseString);
}
} finally {
httpResponse.close();
}
```
这个示例代码中,我们使用了HttpComponents的HttpClient类来创建一个HTTP客户端,然后使用HttpPost类创建一个POST请求,并发送到指定的URL。我们设置了请求头Content-Type为application/json,并设置请求体为JSON格式的字符串。最后,我们读取响应的实体并将其转换为字符串输出。在Python端对应的API接口需要能够接收POST请求,并按照指定的格式返回数据。