2015-12-30 62 views
1

我無法理解下面的捲曲要求:如何在android java中製作相同的cURL請求?

curl -X POST -u "client_id:secret" \ 
    https://bitbucket.org/site/oauth2/access_token -d grant_type=password \ 
    -d username={username} -d password={password} 

我怎樣才能讓在Java(Android版)同樣的要求? 現在,我嘗試這樣:

String auth = vcs.getKey() + ":" + vcs.getSecret(); 
byte[] authEncBytes = Base64.encode(auth.getBytes(), Base64.DEFAULT); 
String authStringEnc = new String(authEncBytes); 
URL url = new URL("https://bitbucket.org/site/oauth2/access_token"); 
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); 
connection.setRequestProperty("Authorization", "Basic " + authStringEnc); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("grant_type", "password"); 
connection.setRequestProperty("username", mLogin); 
connection.setRequestProperty("password", mPassword); 

但它不工作。

回答

1

您正在通過請求標頭傳遞參數。刪除最後三個並替換下面:

String params = "grant_type=password&username=xyz&password="+ java.net.URLEncoder.encode("urp&^!ass", "UTF-8"); 
OutputStream os = connection.getOutputStream(); 
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
writer.write(params); 
writer.flush(); 
writer.close(); 
os.close(); 
int responseCode = connection.getResponseCode(); 
+0

謝謝你的幫助!我會試試看! –