【发布时间】: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"} 但我不能在字符串中使用 "。如果不使用这样的双引号字符,我该如何解决问题" ?