将cURL字符串转换为Resteasy

时间:2014-10-03 11:06:01

标签: java http post curl resteasy

我无法将示例cURL字符串(有效)转换为有意义的resteasy表达式。 cURL是:

curl -X POST -u admin:admin --data-binary "@tempfile.xml" http://localhost:8810/rest/configurations

我有:

public void sendPost(ConfigurationDTO config) throws JAXBException, FileNotFoundException {
    // client target is:  http://localhost:8810/rest
    ResteasyWebTarget target = getTarget();
    target.path("configurations");
    JAXBContext context = JAXBContext.newInstance(ConfigurationDTO.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    // this here produces exactly what I need
    marshaller.marshal(config, new File("test.xml"));

    MultipartFormDataOutput dataOutput = new MultipartFormDataOutput();
    dataOutput.addFormData("file", new FileInputStream(new File("test.xml")), MediaType.APPLICATION_OCTET_STREAM_TYPE);
    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(dataOutput) {};


    Response response = target.request().post( Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));
    response.close();
}

protected ResteasyWebTarget getTarget() {
    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target(UriBuilder.fromUri(restUrl).build());
    client.register(new AddAuthHeadersRequestFilter(user, pass));
    return target;
}

抛出HTTP.500,我无法访问服务器以查看发生的情况。

2 个答案:

答案 0 :(得分:1)

我会尝试在cURL中调试CORS(参见How can you debug a CORS request with cURL?)。在您的情况下,它是一个命令:

curl --verbose -u admin:admin \
  -H "Origin: http://localhost:1234" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS \
  http://localhost:8810/rest/configurations

请将localhost:1234替换为运行RESTEasy客户端的上下文路径。

如果请求不成功,则表示CORS配置存在问题。如果响应包含Access-Control-Allow-Origin标题,则请求成功。

答案 1 :(得分:1)

cURL在使用Content-Type: application/x-www-form-urlencoded参数时发送--data-binary。您正在使用MediaType.MULTIPART_FORM_DATA_TYPE (multipart/form-data),因此我希望您的服务器不接受后者。然后RESTeasy会抛出javax.ws.rs.NotSupportedException: Cannot consume content type

我不明白为什么要将实体编组到文件中并将此文件传递给RESTeasy客户端。使用例如StringWriter您的代码可能如下所示:

StringWriter sw = new StringWriter();
marshaller.marshal(config, sw);
Response response = target.request().post(Entity.entity(sw.toString(), MediaType.APPLICATION_FORM_URLENCODED));

服务器部分是否也由您编写?如果您只发送xml文件application/x-www-form-urlencoded似乎不是最匹配的ContentType。