Android开发: okhttp发个post请求要求Content-Typemultipartform-data有示例代码吗
Sure! Here is an example code to send a POST request using OkHttp library in Android with Content-Type:multipart/form-data.
First, make sure you have added the OkHttp dependency in your app-level build.gradle file:
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
Then, you can use the following code to send a POST request with multipart/form-data content type:
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.File;
import java.io.IOException;
public class OkHttpExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
// Replace the URL with your actual endpoint
String url = "https://example.com/api/upload";
// Replace the file path with the actual file path you want to upload
String filePath = "/path/to/your/file.txt";
File file = new File(filePath);
// Create request body with file and content type
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), file))
.build();
// Create the request with POST method and set the request body
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
// Execute the request and get the response
Response response = client.newCall(request).execute();
// Handle the response here
if (response.isSuccessful()) {
String responseBody = response.body().string();
System.out.println("Response: " + responseBody);
} else {
System.out.println("Request failed with code: " + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Make sure to replace the url variable with the actual URL of your API endpoint and filePath with the actual file path you want to upload.
This code will send a POST request with the specified file as multipart/form-data and print the response from the server. You can modify it according to your specific requirements
原文地址: http://www.cveoy.top/t/topic/h9DH 著作权归作者所有。请勿转载和采集!