我必须测试 EPA 的数据交换 Web 服务。由于很难创建 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() 处引发异常。
我不确定:
- 提交证书的正确方法是什么
- 如果我正确发送凭据
- 如果我的代码不完整,因此应用程序无法获取响应代码
- 我应该使用 Eclipse EE(带有 Web 工具平台)并创建项目 > Web 应用程序,而不是 Eclipse Juno(没有 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();
}
}
}