我正在使用 Maximo 7.5 REST API 并想用 java 编写 REST 客户端来使用这个 RESTful 服务。我在 Maximo 7.5 端启用了 Maximo 安全性,以使 Maximo 用户能够访问其自己的 REST 服务。下面是我的 Maximo RESTful 服务的 web.xml 的样子。
<security-constraint>
<web-resource-collection>
<web-resource-name>REST Servlet for Web App</web-resource-name>
<description>Object Structure Service Servlet (HTTP POST) accessible by authorized users</description>
<url-pattern>/rest/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>Roles that have access to Object Structure Service Servlet (HTTP POST)</description>
<role-name>maximouser</role-name>
</auth-constraint>
<user-data-constraint>
<description>data transmission gaurantee</description>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>REST Web Application Realm</realm-name>
</login-config>
我可以使用 Chrome 的 Postman 插件成功查询 Maximo REST 服务。下面 2 是我的邮递员(REST 客户端)标题。1. MAXAUTH - bWF4YWRtaW46bWF4YWRtaW4= 2. 接受 - 应用程序/xml
虽然我已经在标头中给出了授权(MAXAUTH),但我习惯于弹出窗口输入用户名和密码来查询 Maximo REST 服务。提供凭据后,我会收到响应(如下所示)
下面是我使用相同 RESTful 服务的 Java 代码。我不断收到 401 错误,虽然我将凭据作为财产提供,但它没有授权。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RESTConsume {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {
try {
URL url = new URL("HOSTNAME/maxrest/rest/os/mxperson?personid=maxadmin");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "Application/xml");
connection.setRequestProperty("MAXAUTH", "bWF4YWRtaW46bWF4YWRtaW4=");
System.out.println("Output from Server ....1 \n");
/*
* if (conn.getResponseCode() != 200) {
* System.out.println("Output from Server ....2 \n");
*
* throw new RuntimeException("Failed : HTTP error code : "+
* conn.getResponseCode()); }
*/
System.out.println("Output from Server ....3 \n");
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
System.out.println("Output from Server ....4 \n");
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面是我的输出:
Output from Server ....1
Output from Server ....3
java.io.IOException: Server returned HTTP response code: 401 for URL: http://vhost0043.dc1.co.us.compute.ihost.com/maxrest/rest/os/mxperson?personid=maxadmin
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at RESTConsume.main(RESTConsume.java:35)
它适用于不同的 RESTful 服务(不是 Maximo RESTful 服务),并且未启用我们没有任何安全性的预期响应。如果我需要做一些额外的事情来使用 Maximo RESTful 服务,请告诉我。