如何使用内容类型为 x-www-form-urlencoded 的 okhttp 库 post 数据?

How do I post data using okhttp library with content type x-www-form-urlencoded?

我用过这个方法但是没有post数据。

这是我的代码

 OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {

            Response response = client.newCall(request).execute();
            String responseString = response.body().string();
            response.body().close();
        }catch (Exception e) {
            e.printStackTrace();
        }

我尝试了 DefaultHttpClient ,它似乎可以工作,但它显示已弃用,所以想尝试一些不同的东西..无法弄清楚这有什么问题

你selectMediaType MultipartBuilder.FORM 用于将 file/image 上传为多部分

public static final MediaType FORM = MediaType.parse("multipart/form-data");

尝试像这样发送

private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception { 
    RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build(); 
    Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build(); 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful())
        throw new IOException("Unexpected code " + response); 
    System.out.println(response.body().string()); 
}

对于那些可能仍然会来这里的人,使用 Retrofi2 并将您的数据正确传递到请求正文。即使您设置 "application/x-www-form-urlencoded" 并且没有正确传递数据,您仍然会遇到问题。那是我的情况

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("ContentType", "application/x-www-form-urlencoded");
        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl(URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);

然后确保将数据传递到 api 端点,如下所示。不是 JSON 或 class 对象或字符串,而是请求正文。

RequestBody formBody = new FormBody.Builder()
        .addEncoded("grant_type", "password")
        .addEncoded("username", username)
        .addEncoded("password", password)
        .build();

致电您的 api 服务

Call<Response> call = api.login(formBody);

我希望这对某人有所帮助