2015-12-30 41 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

谢谢你的帮助!我会试试看! –