简体   繁体   English

OkHttp Post未获取服务器端发送的数据

[英]OkHttp Post not getting data sent on the server side

I am trying to send token to the server using OKHTTP library but am not getting the post request sent from the application. 我正在尝试使用OKHTTP库将令牌发送到服务器,但没有收到从应用程序发送的发布请求。

I have already added the internet permission in my Manifest. 我已经在清单中添加了Internet许可。

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

Server 服务器

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

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

Your code looks correct so some more information will be needed. 您的代码看起来正确,因此需要更多信息。 From what is provided my best guess would be http is being redirected to https and maybe losing the POST body or something along those lines. 从提供的内容来看,我最好的猜测是将http重定向到https并可能丢失POST正文或类似内容。

A way to help debug this is to add a NetworkInterceptor that logs the HTTP requests so you can dive into what is actually happening. 一种帮助调试的方法是添加一个记录HTTP请求的NetworkInterceptor ,以便您可以深入了解实际发生的情况。 Here is a runnable example configuring OkHttpClient logging 这是配置OkHttpClient日志记录的可运行示例

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

client.addNetworkInterceptor(logging);

If you can add the debugging output to your question we can dive deeper if there is no issue with http -> https redirects. 如果您可以将调试输出添加到您的问题中,那么如果http-> https重定向没有问题,我们可以进行更深入的研究。

Just a note OkHttpClient are thread safe and are meant to be used by many threads. 请注意, OkHttpClient是线程安全的,并且可以被许多线程使用。 It's good practice to have one OkHttpClient that is reused (per specific configuration). 最好重复使用一个OkHttpClient (按特定配置)。 You can make a static instance or dependency inject it in. Creating one per method call will have overhead. 您可以创建一个静态实例或依赖项以将其注入。每个方法调用创建一个实例将产生开销。

Try this 尝试这个

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

Then Call it 然后叫它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM