android okhttp post
时间: 2023-10-30 08:08:49 浏览: 122
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.
阅读全文
相关推荐

















