dow98764 2015-09-11 15:20
浏览 86

PHP RESTful API访问Jersey客户端POST数据

I am using a PHP RESTful API which is consumed by a Java desktop application using jersey 2.21.

Usually, when I send a POST request from AngularJS, I can access the data via:

$data = json_decode(file_get_contents("php://input"));

However, when I use jersey, the data is put in the $_POST array. Here is my Jersey code:

final HashMap<String, String> params = // some hashmap with a few entries
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
MultivaluedMap formData = new MultivaluedHashMap(params);

WebTarget target = client.target(url);


// Get JSON
String jsonResponse = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);

return jsonResponse;

How do I post the data from Jersey so that I can access it via the above PHP call?

I know I can just use the $_POST array, but I need this API to be consumed from a mobile app, Java desktop & an AngularJS app.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongqing8765 2015-09-11 15:31
    关注

    Thanks to @jonstirling, I got it.

    I had to set the content type as JSON. here is the updated code:

    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);
    
    WebTarget target = client.target(url);
    
    String data = new Gson().toJson(params);
    
    // POST JSON
    Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
    Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
    String jsonResponse = builder.post(json, String.class);
    
    return jsonResponse;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?