使用Java和PHP通过okhttp请求JSON
我将okhttp库与Java和PHP结合使用。我的Java客户端正在运行以下代码使用Java和PHP通过okhttp请求JSON,java,php,json,okhttp,Java,Php,Json,Okhttp,我将okhttp库与Java和PHP结合使用。我的Java客户端正在运行以下代码 public class Connection { public static final MediaType JSON = MediaType .parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url,
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字符串,但我的Web服务只返回空值
<?php
$rawData = file_get_contents("php://input");
$json = json_decode($rawData);
var_dump($json);
?>
我做错了什么?首先,您正在主线程上调用http请求,这将导致错误。所以您使用AsyncTaskok我发现我的json字符串是错误的。我发送了一个错误的字符串{'input':'test},而不是{“input”:“test”},但是我不能在字符串中使用“但我如何解决这个问题而不使用像这样的双引号字符\“?