dongyi3616 2015-03-25 00:33
浏览 332

使用Java和PHP通过okhttp进行JSON请求

I am using okhttp lib with Java and PHP. My Java client is running the following code.

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

On the server-side I try to decode the JSON String with code following below but my webservice just return a NULL.

<?php

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

?>

What am I doint wrong?

  • 写回答

1条回答

  • doujiao9426 2015-07-27 22:49
    关注

    First, you are calling an http request on the main-thread which will cause an error. So you use AsyncTask

    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流