【问题标题】:Android - How to post string parameters to server using okhttpclient?Android - 如何使用 okhttpclient 将字符串参数发布到服务器?
【发布时间】:2017-09-12 05:53:06
【问题描述】:

我想将 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 将这两个参数发送到服务器?

【问题讨论】:

    标签: android http post okhttp


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 2019-10-07
      • 2017-05-10
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多