2013-02-06 103 views
0

我必須測試EPA的Data Exchange 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。我爲我的目的修改了這個。如何從Java應用程序連接到REST Web服務

  1. 隨着證書,則在該行
  2. 沒有證書(註釋)拋出一個錯誤,則連接超時,並在getResponseCode拋出異常()。

我不知道:

  1. 什麼是如果我正確發送憑據
  2. 如果我的代碼是不完整的提交證書
  3. 的正確途徑,因此,應用程序無法獲得響應代碼
  4. 我應該使用Eclipse EE(帶有Web Tools Platform)並創建Project> Web Application,而不是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(); 
     } 

    } 
} 
+0

我知道它晚了...但你有沒有嘗試刪除** uc.setRequestProperty(「Accept」,「text/xml」); ** line? – VaroX

回答

0

你不需要推出自己的。

+0

是的,我知道我可以使用這些客戶端。但是,我應該能夠執行此代碼的一些變體。問題在於它在任何一行都失敗,例如connect(),getResponseCode,getContent等。基本上它不會連接和超時。但它可以使用Chrome或Firefox客戶端。如果有效,我可以運行一個腳本來執行多個POST,這些POST需要使用有效的屬性,計量等創建一個帳戶來生成度量標準(這是我正在測試的)。爲什麼它沒有連接? – dhananjay

0

您正在使用DER文件作爲您的密鑰存儲區,通常不支持Java Crypto。使用keytool創建一個JKS或其他支持的密鑰庫,然後引用它。

相關問題