新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java怎么接收response返回内容,Java怎么接收键盘输入

发布时间:2023-08-31 07:58:39

java怎样接收response返回内容

在Java中可使用HttpURLConnection还是HttpClient来接收response返回内容。
使用HttpURLConnection的示例代码以下:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置要求方法
connection.setRequestMethod("GET");
// 获得响应状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应内容
System.out.println("Response Content: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用HttpClient的示例代码以下:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://example.com");
// 履行要求
HttpResponse response = httpClient.execute(httpGet);
// 获得响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 获得响应内容
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
// 输出响应内容
System.out.println("Response Content: " + content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭HttpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
以上代码示例中,分别使用HttpURLConnection和HttpClient发送GET要求,并接收并输出响应内容。