我有以下成功运行的 REST get 请求:
结果是我随后要解析的 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);
}
但是我该如何进行身份验证呢?我试图为值“Authorization”添加另一个 header 字段,但我没有得到相同的结果。
最佳答案
我认为您必须创建一个 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
编辑:
刚刚尝试了以下代码并在我们受 BASIC 保护的开发环境中成功调用了 REST 服务。
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);
}
关于java - 如何在 Java 中实现这个 REST get 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7725043/