我有以下REST get Request成功运行:
结果是我想要解析的XML文档。我在Java中尝试过相同的东西:
我使用以下代码:
public void getRootService() throws ClientProtocolException, IOException {
HttpGet httpGet = new HttpGet("https://localhost:9443/ccm/rootservices");
httpGet.setHeader("Accept", "text/xml");
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
String projectURL = XMLDocumentParser.parseDocument(in);
System.out.println(projectURL);
HttpGet getProjectsRequest = new HttpGet("https://localhost:9443/ccm/process/project-areas");
getProjectsRequest.setHeader("Content-Type", "application/xml;charset=UTF-8");
getProjectsRequest.setHeader("Accept-Charset", "UTF-8");
getProjectsRequest.setHeader("Accept", "application/xml");
ResponseHandler<String> handler = new BasicResponseHandler();
String projectResponse = client.execute(getProjectsRequest, handler);
//String projectResponse = client.execute(getProjectsRequest, handler);
System.out.println(projectResponse);
}
但我该如何进行身份验证?我试图为“授权”值添加另一个标题字段,但后来我得不到相同的结果。
答案 0 :(得分:5)
我认为你必须创建一个UsernamePasswordCredentials
,类似于(未经测试的);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("somehost", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("username", "password"));
HttpClient httpclient = new DefaultHttpClient();
httpclient.setCredentialsProvider(credsProvider);
请参阅http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
编辑:
刚刚尝试了以下代码,并在我们的开发环境中成功调用了REST服务,该环境受BASIC保护。
public static void main(String[] args) throws ClientProtocolException, IOException {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("dev.*******.com", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("*****", "******"));
DefaultHttpClient client = new DefaultHttpClient();
client.setCredentialsProvider(credsProvider);
String url = "http://dev.******.com:18081/path/to/service/id.xml";
HttpGet get = new HttpGet(url);
ResponseHandler<String> handler = new BasicResponseHandler();
String resp = client.execute(get, handler);
System.out.println(resp);
}
答案 1 :(得分:3)
您可以向Authorization
明确添加HttpRequestBase
标题(HttpGet
,HttpPost
等的抽象类。)
此示例显示了如何制作基本授权值。
String unhashedString = userName + ":" + password;
String hashedString = Base64.encode(unhashedString); //This class doesn't exist, it's for demonstration purpose only.
HttpGet.setHeader("Authorization", "Basic " + hashedString);
在服务器中,你必须反过来(如果你正在进行自己的实现。
答案 2 :(得分:1)
我实现此方法的方法是将会话与标准HTTP控制器一起使用。他们调用登录URL并发布用户和密码,并对会话进行身份验证。完成后,所有后续URL只需检查以确保会话已通过身份验证。
答案 3 :(得分:0)
支持的身份验证机制取决于使用哪个Web服务器来托管Rational Team Concert。 Apache Tomcat服务器使用基本身份验证,而WebSphere Application Server支持基本身份验证和基于表单的身份验证。
您可以查看详细说明here