[英]Calling a webservice from Java
我正在嘗試開發一個Java程序,該程序將僅在目標URL上調用Web服務。
請求方法是POST(不支持GET)。
為此,我正在使用java.net.*
庫。 我想在發布請求中發送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服務。
對於“從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"}
如果JAXB無法解組您的XML,則您的XML無效(即不是真正的XML),或者它與服務器期望的模式不一致。 答案在異常的堆棧跟蹤中的某處,其中應提及為何解組器不喜歡您的XML。
不確定如何進行POST,但是如果使用Apache HttpClient庫,可能會發現事情更簡單。
您能否提供整個例外情況? 沒有這些,就很難知道這是身份驗證問題,編組問題等。
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.