2016-09-26 39 views
1

我能夠在Postman中成功執行GET命令,它返回我需要的各種頭文件。我使用基本身份驗證此第一個GET:Java http GET始終爲空

GET http://SERVER/qcbin/api/authentication/sign-in

我試圖用Java來實現這一點,但什麼都不回來了。我一直得到一個null。

有人能告訴我我做錯了什麼嗎?我無法弄清楚我的錯誤。

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.Base64; 


public class test2 { 

public static void main(String[] args) { 

    try { 
     Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy", 8080)); 
     URL url = new URL ("http://SERVER/qcbin/api/authentication/sign-in"); 

     byte[] credBytes = ("jsmith" + ":" + "abc123").getBytes(); 

     Base64.Encoder base64Encoder = Base64.getEncoder().withoutPadding(); 
     String encoding = base64Encoder.encodeToString(credBytes); 

     HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); 
     connection.setRequestMethod("GET"); 
     connection.setDoOutput(true); 
     connection.setRequestProperty ("Authorization", "Basic " + encoding); 

內容在下列行後設置爲空。

 InputStream content = (InputStream)connection.getInputStream(); 
     BufferedReader in = 
      new BufferedReader (new InputStreamReader (content)); 
     String line; 
     while ((line = in.readLine()) != null) { 
      System.out.println(line); 
     } 
    } catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

你做你的郵遞員在機器上測試java代碼運行?你可以發表你的請求的'curl -vvv'嗎? – 2016-09-26 18:10:39

+0

你爲什麼要調用'setDoOutput(true)'?在這種情況下,連接不會期望一些輸出嗎? –

+0

@RC - 是的,同一臺機器。我是非常新的Java。我不熟悉捲曲。 –

回答

0

在你正在閱讀從流線下面的代碼:

while ((line = in.readLine()) != null) { 
    System.out.println(line); 
} 

難道你從來沒有從信息流這意味着服務器收到「線的新」字不向您發送以新行字符結尾的數據?所以當沒有更多的數據通過你的流時,in.readLine()還在等待那個行結束字符?

嘗試用替換代碼:

 // reads to the end of the stream 
    while((value = br.read()) != -1) 
    { 
     // converts int to character 
     char c = (char)value; 

     // prints character 
     System.out.println(c); 
    } 

編輯:從BufferedReader中的javadoc:

公共字符串的readLine() 拋出IOException讀取一行文本。

一條線被換行符('\ n'),一個 回車符('\ r')或一個回車符後跟一個 換行符。

返回:包含行的內容,而不是 包括任何行終止字符的字符串,或NULL,如果 流的末尾已到達

+0

這不可能是問題 - 無論如何readLine()在達到流末尾時都會返回null。 –

+0

當然,由於流被沖洗和關閉 –