我正在尝试将POST
Request发送到我的服务器,该服务器返回JSONObject
,但是它需要这个长字符串形式的参数:
CLIENT_ID = client_id
&安培; client_secret = client_secret
&安培; grant_type =密码&安培;用户名= username
&安培;密码= password
我一直在试图弄清楚如何做到这一点,但是每个与此相似的教程或答案都使用折旧的HTTPClient
等。有人可以指出我正确的方向吗?
答案 0 :(得分:1)
HttpClient
已被删除
使用HttpURLConnection
代替,示例为here。您还可以阅读此post了解更多信息。
答案 1 :(得分:0)
您可以使用此代码:
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的响应 享受你的代码:)
答案 2 :(得分:0)
试试这个
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);