我的要求是使用PUT
,向服务器发送标题和正文,这将更新数据库中的内容。
我刚刚阅读okHttp documentation并尝试使用他们的POST
示例,但它对我的用例不起作用(我认为这可能是因为服务器需要我使用PUT
代替POST
)。
这是我使用POST
的方法:
public void postRequestWithHeaderAndBody(String url, String header, String jsonBody) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", header)
.build();
makeCall(client, request);
}
我试图使用PUT
搜索okHttp示例但没有成功,如果我需要使用PUT
方法,那么无论如何都要使用okHttp?
我使用的是okhttp:2.4.0(以防万一),感谢任何帮助!
答案 0 :(得分:9)
使用.post
.put
public void putRequestWithHeaderAndBody(String url, String header, String jsonBody) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.put(body) //PUT
.addHeader("Authorization", header)
.build();
makeCall(client, request);
}
答案 1 :(得分:3)
Request request = new Request.Builder()
.url(url)
.put(body) // here we use put
.addHeader("Authorization", header)
.build();
答案 2 :(得分:2)
如果您使用的是OkHttp版本2.x,请使用以下命令:
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodingBuilder()
.add("Key", "Value")
.build();
Request request = new Request.Builder()
.url("http://www.foo.bar/index.php")
.put(formBody) // Use PUT on this line.
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected response code: " + response);
}
System.out.println(response.body().string());
由于OkHttp版本3将FormEncodingBuilder
替换为FormBody
和FormBody.Builder()
,因此对于版本3.x,您必须执行以下操作:
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
Request request = new Request.Builder()
.url("http://www.foo.bar/index.php")
.put(formBody) // PUT here.
.build();
try {
Response response = client.newCall(request).execute();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}