【问题标题】:OkHttp Post not getting data sent on the server sideOkHttp Post 没有收到服务器端发送的数据
【发布时间】:2017-12-28 16:23:08
【问题描述】:

我正在尝试使用 OKHTTP 库向服务器发送令牌,但没有收到应用程序发送的发布请求。

我已经在我的 Manifest 中添加了互联网权限。

private void registerToken(String token) {

        final OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("token", token)
                .build();

        Request request = new Request.Builder()
                .url("http://####/push_notifcation/index.php")
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();

            Log.i(TAG, "ok");
            Log.i(TAG, response.message());
        } catch (IOException e) {
            e.printStackTrace();

            Log.i(TAG, e.getMessage());
            Log.i(TAG, "nok");
        }
    }

服务器

if(isset($_POST["token"])){
    $token = $_POST["token"];

    $db_data = $database->insert("tokens", [
        "token" => $token
    ]);
}

【问题讨论】:

    标签: java android post okhttp


    【解决方案1】:

    您的代码看起来正确,因此需要更多信息。从所提供的内容来看,我最好的猜测是 http 被重定向到 https 并且可能会丢失 POST 正文或类似的内容。

    一种帮助调试的方法是添加一个NetworkInterceptor 来记录 HTTP 请求,这样您就可以深入了解实际发生的情况。这是一个配置OkHttpClient logging的可运行示例

    Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    HttpLoggingInterceptor logging =
        new HttpLoggingInterceptor((msg) -> {
            logger.debug(msg);
        });
    logging.setLevel(Level.BODY);
    
    client.addNetworkInterceptor(logging);
    

    如果您可以将调试输出添加到您的问题中,如果 http -> https 重定向没有问题,我们可以深入研究。

    请注意OkHttpClient 是线程安全的,并且可以被许多线程使用。拥有一个可重复使用的OkHttpClient 是一种很好的做法(根据特定配置)。你可以创建一个静态实例或依赖注入它。每个方法调用创建一个会产生开销。

    【讨论】:

      【解决方案2】:

      试试这个

      public static void send(JSONObject obj){
          new OkHttpClient().newCall(new Request.Builder()
                  .addHeader("Content-Type", "application/json")
                  .url("URL...")
                  .post(RequestBody.create(
                          MediaType.parse("application/json; charset=utf-8"),
                          obj.toString())
                  ).build())
          .enqueue(new Callback() {
              @Override
              public void onFailure(Call call, IOException e) {
                  Log.d("ZAKA",e.getMessage());
              }
              @Override
              public void onResponse(Call call, Response response) throws IOException {
                  Log.d("ZAKA","Report : -> "+response.body().string());
              }
          });
      }
      

      然后调用它

      JSObject obj = new JSObject();
      obj.put("token","your token");
      send(obj); // Call send method
      

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        • 2017-01-19
        • 2020-04-13
        • 2017-05-04
        • 2019-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多