from 數據如下
key=value&other=data
String url = "https://api.netkiller.cn/oauth/token"; OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("grant_type", "password") .add("username", "netkiller") .add("password", "123456") .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("伺服器端錯誤: " + response); }
POST RAW Json 數據,數據的形態這樣的
{"key":"value"}
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); }
OkHttpClient client = new OkHttpClient(); final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain"); final String postBody = "Hello World"; RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_TEXT; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8(postBody); } @Override public long contentLength() throws IOException { return postBody.length(); } }; Request request = new Request.Builder() .url("https://www.google.com") .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("伺服器端錯誤: " + response); } System.out.println(response.body().string());