2016-03-07 119 views
0

我必須向api發出請求。 的作品的捲曲是:在java中請求curl

curl -u apiKey:pass -H "Accept: application/json" https://subdomain.chargify.com/portal/customers/id/management_link.json 

和Java代碼,我至今是:

String userpass = apiKey + ":" + pass; 
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())); 

URL url = new URL(stringUrl); 
HttpURLConnection uc = (HttpURLConnection) url.openConnection(); 
uc.setRequestProperty("Accept", "application/json"); 
uc.setRequestProperty("Authorization", basicAuth); 

InputStream content = uc.getInputStream(); 
int status = uc.getResponseCode(); 
BufferedReader in = new BufferedReader (new InputStreamReader(content)); 

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

每次我得到一個401響應代碼。 我在做什麼錯?

回答

1

您的請求需要用戶進行身份驗證。由於請求中已包含授權憑證,因此401響應表明授權已被拒絕用於這些憑證。檢查你如何生成和驗證密鑰

+0

你說得對。憑證表單是apiKey:x,其中x是密碼。我將API密鑰保存在應用程序屬性文件中,比如「apikey」,當我使用它時,它變成了「」apikey「」。謝謝。 –