2016-03-07 108 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“”。谢谢。 –