从Java调用Web服务

时间:2011-03-08 07:51:09

标签: java post httpclient

我正在尝试开发一个简单地在目标URL上调用web服务的Java程序。

请求方法是POST,(不支持GET)。

为此我在我的程序中使用java.net.*库。我想在post请求中发送一个xml文件。每当我运行客户端程序时,它都会给我以下错误:

java.io.IOException:server returned response code 500

然后,当我签入服务器日志时,会出现以下异常:

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:.....

在服务器端我使用的是jaxb2marshaller,框架是spring 3.0 mvc。

所有其他客户端(例如php)都可以使用php cURL调用相同的web服务。

4 个答案:

答案 0 :(得分:0)

如果JAXB无法解组您的XML,那么您的XML无效(即,实际上不是XML),或者它不符合服务器期望的架构。答案是异常的堆栈跟踪中的某个位置,应该提到为什么unmarshaller不喜欢你的XML。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

你能提供整个例外吗?没有它,很难知道它是一个身份验证问题,一个编组问题等等。

HttpClient def工作,结帐Play的WS库: http://www.playframework.org/documentation/api/1.1.1/play%2Flibs%2FWS.html

答案 3 :(得分:0)

对于“从Java调用Web服务”,我们可以发出简单的GET或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");
    }
}

我已使用“ https://jsonplaceholder.typicode.com”来实现此POST请求。通过此网站,我们可以执行GET和POST并测试我们的Web服务。

输出将是:

    {
      "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"}
相关问题