如何在使用Jersey的WebResource进行POST时发送表单数据?

时间:2016-08-24 20:39:40

标签: java post jersey jersey-client

我有一个Postman POST请求,如下所示:

enter image description here

我使用泽西的WebResource将以上内容映射到代码中的代码如下,但它不起作用:

Client authKeyClient = Client.create();
WebResource webResource = authKeyClient.resource("https://ims-na1-stg1.company.com/token/v1");
String input = "{\"grant_type\":\"authorization_code\",\"client_id\":\"orders\",\"client_secret\":\"0af3b233-f1ca-41da-a0fa-61c08d15cadc\",\"code\":\"eyJhbGciOiJSUzI1NiIsIng1dSI6Imltc19uYTEtc\"}";
currentEnv.getImsSecret()).header("code", currentEnv.imsCode).get(String.class);
String response = webResource.post(String.class, input);

我最终获得400 Bad Request。我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试添加Content-Type。我还建议以更有条理的方式发送请求以避免错误输入错误:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .post(ClientResponse.class, formData);

类似的讨论:Using the Jersey client to do a POST operation