OkHttpClient使用实例
时间: 2023-09-08 22:08:07 浏览: 118
以下是使用OkHttpClient的示例代码:
```
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpClientExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// 创建请求
Request request = new Request.Builder()
.url("http://www.example.com")
.build();
try {
// 发送请求并获取响应
Response response = client.newCall(request).execute();
// 输出结果
System.out.println("Response code: " + response.code());
System.out.println("Response body: " + response.body().string());
// 关闭响应
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码展示了如何使用OkHttpClient发送一个简单的GET请求,并打印出响应的状态码和响应体内容。你可以根据需要修改URL和请求头信息。请确保你已经在项目中添加了OkHttp库的依赖。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [OKHttpClient使用示例](https://blog.csdn.net/weixin_34146986/article/details/92262550)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [OkHttpClient使用教程详解](https://blog.csdn.net/sshduanzhijun/article/details/124642366)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文