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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制