2013-03-22 123 views
0

我必須從tsa服務器獲取時間戳。我正在發送一個文件(轉換爲byte[])。
但是,當我嘗試獲得響應時,它會拋出一個NullPointerException來自時間戳響應的錯誤

這是我的代碼:

public static void timeStampServer() throws IOException{ 
     //String TSA_URL1 = "http://tsa.starfieldtech.com/"; 
     String TSA_URL2 = "http://ca.signfiles.com/TSAServer.aspx"; 
     //String TSA_URL3 = "http://timestamping.edelweb.fr/service/tsp"; 
     try { 
      byte[] digest = leerByteFichero("C:\\deskSign.txt"); 

      TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator(); 
      TimeStampRequest req = reqgen.generate(TSPAlgorithms.SHA1, digest); 
      byte request[] = req.getEncoded(); 

      URL url = new URL(TSA_URL2); 
      HttpURLConnection con = (HttpURLConnection) url.openConnection(); 

      con.setDoOutput(true); 
      con.setDoInput(true); 
      con.setRequestMethod("POST"); 
      con.setRequestProperty("Content-type", "application/timestamp-query"); 

      con.setRequestProperty("Content-length", String.valueOf(request.length)); 

      if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); 
      } 
      InputStream in = con.getInputStream(); 
      TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject()); 
      TimeStampResponse response = new TimeStampResponse(resp); 
      response.validate(req); 
      System.out.println(response.getTimeStampToken().getTimeStampInfo().getGenTime()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

我試着用3 TSA服務器,但它們中的任何返回我一個有效的TSA。
所有人都會在
TimeStampResponse response = new TimeStampResponse(resp);」中拋出NullPointerException。

TSA_URL2拋出一個

java.io.IOException: Received HTTP error: 411 - Length Required.

我不知道問題出在TSA服務器或在我的代碼。任何人都可以幫助我?

+0

我忘了說,leerByteFichero函數只是讀一個文件並將其轉換爲一個字節[] – Ainur 2013-03-22 08:57:48

回答

1

我可以看到的問題在於你的請求(NullPointer來自空的resp,因爲你沒有迴應)。具體來說,問題是你的HTTP請求頭後沒有冒號。這會使服務器無法讀取強制性的Content-length標頭。從RFC2616第4.2節(HTTP DOC):

HTTP header fields, which include general-header (section 4.5), request-header (section 5.3), response-header (section 6.2), and entity-header (section 7.1) fields, follow the same generic format as that given in Section 3.1 of RFC 822. Each header field consists of a name followed by a colon (":") and the field value.

TL; DR:

變化:

 con.setRequestProperty("Content-type", "application/timestamp-query"); 
     con.setRequestProperty("Content-length", String.valueOf(request.length)); 

到:

 con.setRequestProperty("Content-type:", "application/timestamp-query"); 
     con.setRequestProperty("Content-length:", String.valueOf(request.length)); 
+0

你是對的,這就是問題所在。現在它引發另一個異常:java.lang.IllegalArgumentException:'TimeStampResp'工廠中的未知對象:org.bouncycastle.asn1.DERUnknownTag創建TimeStampResp對象 – Ainur 2013-03-22 09:57:01

+1

+1此答案解決了最初的問題,對於新問題也許它是最好再問一個問題。 – dcernahoschi 2013-03-22 10:11:25