【问题标题】:JSON Request via okhttp with Java and PHP使用 Java 和 PHP 通过 okhttp 请求 JSON
【发布时间】:2015-05-28 12:34:54
【问题描述】:

我正在使用带有 Java 和 PHP 的 okhttp 库。我的 Java 客户端正在运行以下代码。

public class Connection {

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


    public static void main(String[] args) throws IOException {
        Connection example = new Connection();
        String json = "{'input':'test'}";
        String response = example.post("http://localhost/android_api/index.php", json);
        System.out.println(response);
    }
}

在服务器端,我尝试使用下面的代码解码 JSON 字符串,但我的网络服务只返回 NULL。

<?php

    $rawData = file_get_contents("php://input");
    $json = json_decode($rawData);
    var_dump($json);

?>

我做错了什么?

【问题讨论】:

  • 好的,我发现我的 json 字符串是错误的。我发送了错误的字符串 {'input':'test'} 而不是 {"input":"test"} 但我不能在字符串中使用 "。如果不使用这样的双引号字符,我该如何解决问题" ?

标签: java php json okhttp


【解决方案1】:

首先,您在主线程上调用 http 请求,这将导致错误。所以你使用 AsyncTask

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 2015-07-24
    • 2017-03-24
    • 2020-03-28
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多