httpresponse获取返回body
时间: 2024-09-24 21:16:56 浏览: 41
java获取http请求的Header和Body的简单方法
5星 · 资源好评率100%
当你使用HTTP客户端(如Java的HttpURLConnection、HttpClient,Python的requests库等)发送请求并获取响应时,通常会得到一个HttpResponse对象。这个对象包含有关响应的各种信息,包括状态码、头信息以及响应体。在许多编程语言中,响应体通常存储在一个流(stream)或者字符串中,你可以通过以下步骤获取:
1. 对于Java的HttpURLConnection:
```java
InputStream inputStream = httpResponse.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
reader.close();
```
2. Python的requests库:
```python
response = requests.get('http://example.com')
response_body = response.text
```
3. JavaScript (fetch API):
```javascript
fetch('http://example.com')
.then(response => response.text())
.then(responseBody => console.log(responseBody))
.catch(error => console.error(error));
```
阅读全文