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

douganggu4392
douganggu4392 你是对的,我修好了。谢谢
接近 5 年之前 回复
donglizhan7848
donglizhan7848 再一次,猜测(我不使用java,更不用说泽西岛),但你可能会在MediaType.APPLICATION_JSON_TYPE之后,假设你实际上正在传递JSON,这是你的PHP应用程序所期望的。
接近 5 年之前 回复
douting1871
douting1871 嘿@JonStirling,我觉得它与标题有关。试着弄清楚如何设置JSON标题。
接近 5 年之前 回复
dregvw1801
dregvw1801 猜猜暗示。您的问题是MediaType.APPLICATION_FORM_URLENCODED_TYPE。
接近 5 年之前 回复

1个回答



感谢@jonstirling,我明白了。 </ p>

我必须将内容类型设置为JSON。 这是更新的代码:</ p>

  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;
</ code> </ pre>
</ div>

展开原文

原文

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;

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐