我使用过这种方法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,这似乎有效,但它显示已弃用,所以想到尝试不同的东西......不能弄清楚这是什么问题
答案 0 :(得分:26)
您选择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());
}
答案 1 :(得分:0)
对于那些仍可能出现在此处的用户,请与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);
我希望这对某人有帮助