Android - 如何使用okhttpclient将字符串参数发布到服务器?

时间:2017-04-16 12:57:27

标签: android http post okhttp

我想将2个参数 - 设备uuid,google id - 发布到服务器。我使用OkhttpClient,所以我写了这样的代码:

        OkHttpClient client = new OkHttpClient();

        FormBody.Builder formBuilder = new FormBody.Builder()
                .add("uuid", "123456789123")
                .add("google_id", "testgoogleid");

        RequestBody formBody = formBuilder.build();

        Request request = new Request.Builder()
                .url("http://ip:port/signup?")
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        Log.d("Response", response.body().string());

我知道Formbody.Builder正在发出http请求,但是response.body()。string()是:

  

{" message":"浏览器(或代理)发送了此服务器无法理解的请求。"}

如何使用POST和OkhttpClient将这两个参数发送到服务器?

1 个答案:

答案 0 :(得分:0)

选中此link

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