如何从Java应用程序连接到RESTWeb服务
我必须测试EPA的数据交换网络服务。因为很难创建100个帐户、建筑物、能源使用分布等,所以我想自动化这个过程。我搜索了一些代码示例来实现一个简单的GET。我发现最好的是在http://pic.dhe.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.taddm.doc_7.2%2FSDKDevGuide%2Ft_cmdbsdk_restapi_java.html。我为了我的目的修改了这个
- 对于证书,它在该行抛出一个错误
- 如果没有证书(注释掉),连接将超时并在getResponseCode()处引发异常李>
我不确定:
- 提交证书的正确方式是什么
- 如果我正确发送凭据
- 如果我的代码不完整,因此应用程序无法获取响应代码
- 我应该使用EclipseEE(带有Web工具平台)并创建项目>;Web应用程序,而不是EclipseJuno(没有WTP)
先谢谢你
package Package1;
import java.io.*;
import java.util.*;
import java.lang.StringBuffer;
import java.net.*;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
public class Class1 {
public static void main (String args[]){
try{
// set this property to the location of the cert file
System.setProperty("javax.net.ssl.trustStore","C:/Documents and Settings/bhattdr/Desktop/-.energystar.gov.der");
String username = "yy777PPP";
String password = "yy777PPP";
String userpass = "";
URL url = new URL("https://portfoliomanager.energystar.gov/wstest/account");
// URLConnection uc = url.openConnection();
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
System.out.println("sending request...");
uc.setRequestMethod("GET");
uc.setAllowUserInteraction(false);
uc.setDoOutput(true);
uc.setRequestProperty( "Content-type", "text/xml" );
uc.setRequestProperty( "Accept", "text/xml" );
uc.setRequestProperty ("Authorization", basicAuth);
System.out.println(uc.getRequestProperties());
// uc.setRequestProperty( "authorization", "Basic " + encode("administrator:collation"));
// Map headerFields = uc.getHeaderFields();
// System.out.println("header fields are: " + headerFields);
int rspCode = uc.getResponseCode();
if (rspCode == 200) {
InputStream is = uc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String nextLine = br.readLine();
while (nextLine != null) {
System.out.println(nextLine);
nextLine = br.readLine();
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
# 1 楼答案
您正在使用DER文件作为密钥存储,而Java Crypto通常不支持该文件。使用keytool创建JKS或其他受支持的密钥库,然后引用它
# 2 楼答案
在所有REST客户端框架中。。。你试过OpenFaign吗?这是NetFlix堆栈中的一个组件。易于使用,适合所有其他产品 NetFlix的组件
试试看:https://github.com/OpenFeign/feign
# 3 楼答案
你不需要自己动手