android okhttp post
时间: 2023-10-30 20:08:49 浏览: 119
To make a POST request using OkHttp in Android, follow these steps:
1. Add OkHttp library to your project by adding the following dependency in your app-level build.gradle file:
```
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
```
2. Create an instance of OkHttpClient:
```
OkHttpClient client = new OkHttpClient();
```
3. Create a RequestBody object with your request data:
```
RequestBody requestBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.build();
```
4. Create a Request object with your URL and RequestBody:
```
Request request = new Request.Builder()
.url("http://example.com/api")
.post(requestBody)
.build();
```
5. Execute the request using the OkHttpClient object:
```
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
// process response data
} catch (IOException e) {
e.printStackTrace();
}
```
Note: Replace "http://example.com/api" with your actual URL and "key1", "value1", "key2", "value2" with your actual request data.
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)