【问题标题】:Https post request with json response android error带有json响应android错误的Https post请求
【发布时间】:2013-03-04 06:39:40
【问题描述】:

我正在连接到 Restful Web 服务并获取 JSON 响应。

我能够发送请求并在 JSON 对象中处理响应,但问题是我收到错误:

Invalid api_key(is a parameter that I send,but I am sure is right).

您能否帮我了解一下我的代码或 WEB 是否有问题?

HttpClient httpClient = new DefaultHttpClient();
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("SSLSocketFactory", SSLSocketFactory.getSocketFactory(), 443));
HttpPost request = new HttpPost();
request.setHeader("Content-type", "application/json, charset=utf-8");
request.setHeader("Accept", "application/json");
URI targetUri = new URI(TARGET_URL);
request.setURI(targetUri);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("api_key", "api_key"));
postParameters.add(new BasicNameValuePair("user[email]", email));
postParameters.add(new BasicNameValuePair("user[password]",pwd));

Log.i("","EMAIL REQUEST: "+email.toString());
Log.i("","PWD REQUEST: "+pwd.toString());
HttpEntity postEntity = new UrlEncodedFormEntity(postParameters,"UTF-8");
request.setEntity(postEntity);
Log.i("","Request header "+request.getRequestLine());
Log.i("","Request : " +EntityUtils.toString(request.getEntity()));

httpClient.execute(request, myResponseHandler);

【问题讨论】:

  • 方案构造函数在参数中采用方案的值。在你的情况下,“https”,而不是“SSLSocketFactory”。
  • 那你是在声明content-type application/json,但是你真的是在sendind application/x-www-form-urlencoded
  • 那么你似乎没有对 execute 的结果做任何事情?
  • 引导查找错误的来源:记录您的请求,使用参考实现使用 curl 进行测试(通常使用 curl),比较两者。
  • 你好 njzk2,谢谢你回答我。使用 SSLSocketFactory 只是因为我没有收到证书,所以我实现它只是为了管理那个错误。请求必须是 POST 和响应将是 json,所以如果该代码错误,我该如何管理它?结果在代码的另一部分进行管理,并从字符串中的 json 解析

标签: android rest http-post


【解决方案1】:

您正在处理的服务似乎需要 API KEY 中的 ACTUAL 值: postParameters.add(new BasicNameValuePair("api_key", "apy_key"));

将第二个操作数替换为您提供的 APIkey。

【讨论】:

  • 我还打印了响应状态行并且是 401,这意味着,也许,我发送的参数有问题。