向请求添加参数

Add Parameters to a Request

我正在尝试将 POST Request 发送到我的服务器,其中 returns 是 JSONObject,但是它需要这种长字符串形式的参数:

client_id=client_id&client_secret=client_secret&grant_type=密码&用户名=username&密码=password

我一直在努力弄清楚如何做到这一点,但是每个教程或与此类似的答案都使用折旧的 HTTPClient 等。有人能指出我正确的方向吗?

HttpClient 从 API 级别 22

开始被描述

使用HttpURLConnection instead, examples are here. You can also read this post了解更多。

我建议使用 Retrofit as it makes managing JSON requests into POJOs 更简单。

您可以使用此代码:

 public JSONObject getJSONObject(String url, List<NameValuePair> parameters) {

    HttpPost httpPost = new HttpPost(url);
   /* httpPost.setHeader("Content-type", "application/json");
    httpPost.setHeader("Accept", "application/json");*/
    httpPost.addHeader("api_key", mContext.getResources().getString(R.string.api_key));
    HttpResponse response = null;
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(parameters));
        response = mHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String jsonResponse = EntityUtils.toString(entity);
        for (NameValuePair params : parameters) {
            Log.d("params:", params.toString());
        }
        Log.d("url:", url);
        Log.d("EntityUtils", jsonResponse);
        JSONObject jsonObject = new JSONObject(jsonResponse);
        return jsonObject;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;

}

并像这样调用此方法:

 public String setCricketInfo(String userId, String role, String battingStyle) {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair(mContext.getString(R.string.role_json), role));
    JSONObject jsonObject = this.getJSONObject(BASE_URL, parameters);
    try {
        return jsonObject.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

现在可以向远程发送请求并获得响应 Json 享受你的代码:)

试试这个

List<NameValuePair> params = new ArrayList<>();
params.add("client_id", client_id);
params.add("client_secret", client_secret);
params.add("grant_type", password);
params.add("username", username);
params.add("password", password);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://server.com", URLEncodedUtils.format(params, "utf-8"), handler, handler);