如何从Java应用程序连接到RESTWeb服务
我必须测试EPA的数据交换网络服务。因为很难创建100个帐户、建筑物、能源使用分布等,所以我想自动化这个过程。我搜索了一些代码示例来实现一个简单的GET。我找到的最好的是在。我为了我的目的修改了这个如何从Java应用程序连接到RESTWeb服务,java,web-services,rest,Java,Web Services,Rest,我必须测试EPA的数据交换网络服务。因为很难创建100个帐户、建筑物、能源使用分布等,所以我想自动化这个过程。我搜索了一些代码示例来实现一个简单的GET。我找到的最好的是在。我为了我的目的修改了这个 对于证书,它在该行抛出一个错误 如果没有证书(注释掉),连接将超时并在getResponseCode()处引发异常 我不确定: 提交证书的正确方式是什么 如果我正确发送凭据 如果我的代码不完整,因此应用程序无法获取响应代码 我应该使用EclipseEE(带有Web工具平台)并创建Project>We
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();
}
}
}
你不需要自己动手
- 如果您想写一些东西,可以使用Jersey,它有现有的类作为Rest客户机()
- 如果你不想写东西,有很多应用程序可以使用RESTAPI。谷歌出现了很多(比如)
试试看:是的,我知道我可以使用这些客户端。但是,我应该能够执行此代码的一些变体。问题是它在任何一行都失败了,例如connect()、getResponseCode、getContent等等。基本上,它没有连接和超时。但它可以使用Chrome或Firefox客户端。如果可行的话,我可以运行一个脚本来完成创建一个具有有效属性、度量等的帐户所需的多个帖子,以生成度量(这就是我正在测试的)。为什么不联系?我知道已经很晚了。。。但是您是否尝试删除uc.setRequestProperty(“Accept”、“text/xml”);行??单击链接并滚动至基本。。。但我当然应该把它复制到这里。对不起