简体   繁体   English

从Java调用Web服务

[英]Calling a webservice from Java

I am trying to develop a Java program that will simply call a webservice on a target URL. 我正在尝试开发一个Java程序,该程序将仅在目标URL上调用Web服务。

Request method is POST, (GET not supported). 请求方法是POST(不支持GET)。

For this in my program I am using java.net.* library. 为此,我正在使用java.net.*库。 I want to send an xml file in the post request. 我想在发布请求中发送xml文件。 Whenever i run the client program it gives me following error: 每当我运行客户端程序时,都会出现以下错误:

java.io.IOException:server returned response code 500

Then when I check in the server logs there is following exception: 然后,当我检查服务器日志时,出现以下异常:

org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/targetdirectory] threw exception [Request processing failed; nested exception is org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
 - with linked exception:.....

On the server side I am using jaxb2marshaller, framework is spring 3.0 mvc. 在服务器端,我正在使用jaxb2marshaller,框架是spring 3.0 mvc。

All the other clients such as in php are able to invoke the same webservice using php cURL. 所有其他客户端(例如php中的客户端)都可以使用php cURL调用相同的Web服务。

For "Calling a webservice from Java" we can issue simple GET or POST requests. 对于“从Java调用Web服务”,我们可以发出简单的GET或POST请求。

Below is the code for POST (as requirement is for post): 以下是POST的代码(要求是发布):

public static void MyPOSTRequest() throws IOException {
    final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" + "    \"id\": 101,\r\n"+ "    \"title\": \"Test Title\",\r\n" + "    \"body\": \"Test Body\"" + "\n}";
    System.out.println(POST_PARAMS);
    URL obj = new URL("https://jsonplaceholder.typicode.com/posts");
    HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("userId", "a1bcdefgh");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    OutputStream outputStream = postConnection.getOutputStream();
    outputStream.write(POST_PARAMS.getBytes());
    outputStream.flush();
    outputStream.close();
    int responseCode = postConnection.getResponseCode();
    System.out.println("POST Response Code :  " + responseCode);
    System.out.println("POST Response Message : " + 
    postConnection.getResponseMessage());
    if (responseCode == HttpURLConnection.HTTP_CREATED) {
        BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString()); // print result
    } else {
        System.out.println("POST NOT WORKED");
    }
}

I have used " https://jsonplaceholder.typicode.com " to achieve this POST Request. 我已经使用“ https://jsonplaceholder.typicode.com ”来实现此POST请求。 Through this website we can perform both GET and POST and test our webservices. 通过此网站,我们可以执行GET和POST并测试我们的Web服务。

Output will be : 输出将是:

    {
      "userId": 101,
     "id": 101,
     "title": "Test Title",
     "body": "Test Body"
     }
 POST Response Code : 201
 POST Response Message : Created
 {  "userId": 101,  "id": 101,  "title": "Test Title",  "body": "Test Body"}

If JAXB is unable to unmarshal your XML, then either your XML is invalid (ie is not really XML), or it doesn't conform with the schema expected by the server. 如果JAXB无法解组您的XML,则您的XML无效(即不是真正的XML),或者它与服务器期望的模式不一致。 The answer is somewhere in the stack trace of the exception, which should mention why the unmarshaller didn't like your XML. 答案在异常的堆栈跟踪中的某处,其中应提及为何解组器不喜欢您的XML。

不确定如何进行POST,但是如果使用Apache HttpClient库,可能会发现事情更简单。

Can you provide the whole exception? 您能否提供整个例外情况? Without that, it's hard to know if it's an authentication problem, a marshalling problem, etc. 没有这些,就很难知道这是身份验证问题,编组问题等。

HttpClient def works, checkout Play's WS library as well: http://www.playframework.org/documentation/api/1.1.1/play%2Flibs%2FWS.html HttpClient def可以正常运行,还可以检出Play的WS库: http : //www.playframework.org/documentation/api/1.1.1/play%2Flibs%2FWS.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM