如何在android java中做同样的cURL请求? [英] How to make same cURL request in android java?

查看:274
本文介绍了如何在android java中做同样的cURL请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解下面的cURL请求:

I cannot understand request below for 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)中提出同样的请求?
现在,我尝试这样:

How can I make same request in java (Android)? Now, I try so:

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

但不起作用。

推荐答案

您正在传递的post参数与请求头。删除最后三个,并替换为以下内容:

You are passing the post parameters with at request header. Remove the last three and replace with below:

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

这篇关于如何在android java中做同样的cURL请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆