23

我使用了这种方法https://stackoverflow.com/a/31744565/5829906但没有发布数据。

这是我的代码

 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 ,这似乎可以正常工作,但它显示已弃用,所以想尝试一些不同的东西..无法弄清楚这有什么问题

4

2 回答 2

35

您选择MediaType MultipartBuilder.FORM 哪个用于将文件/图像作为多部分上传

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()); 
}

于 2016-07-27T07:52:37.507 回答
3

对于那些可能仍然来到这里的人,使用 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,也不是类对象或字符串,而是请求正文。

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

调用你的 api 服务

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

我希望这可以帮助某人

于 2019-10-13T00:53:13.843 回答