2014-10-03 62 views
0

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

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,我没有对服务器的访问,看看发生了什么。

+0

首先我错过了代码中的用户密码信息。 – Tomas 2014-10-03 11:34:43

+0

它在'getTarget()'中完成,GET请求也可以工作,所以没有问题。 – 2014-10-03 11:37:41

+0

我是否应该理解您可以通过RESTEasy客户端调用GET请求,并且它可以工作? – Tomas 2014-10-03 11:40:52

回答

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 

请与您的客户端的RESTEasy上运行的上下文路径替换localhost:1234

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

+0

cURL调用正在工作,问题在于RESTeasy代码。此外,这里也可以不存在CORS问题,因为curl和RESTeasy客户端都没有同源策略。 – lefloh 2014-10-03 16:28:12

1

当使用--data-binary参数时,cURL发送Content-Type: application/x-www-form-urlencoded。你正在使用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。

+0

感谢您的输入。写入文件主要是为了调试目的。服务器不是由我写的,它就像一个黑匣子,我只是在我们使用它时进行测试。我会在星期一尝试你的建议。 – 2014-10-03 20:17:44