【问题标题】:How to make same cURL request in android java?如何在android java中发出相同的cURL请求?
【发布时间】:2015-12-30 00:42:30
【问题描述】:

我无法理解下面的 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);

但它不起作用。

【问题讨论】:

    标签: java android curl


    【解决方案1】:

    您正在使用 at 请求标头传递 post 参数。删除最后三个并替换为以下内容:

    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();
    

    【讨论】:

    • 感谢您的帮助!我试试看!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2013-01-05
    相关资源
    最近更新 更多