我有以下代码从我的android应用程序连接到zappos api服务器并搜索一些东西。但是它要么返回error 404 or We are unable to process the request from the input feilds given
。
当我执行相同的查询时,它可以在Web浏览器上运行。
查询是:http://api.zappos.com/Search&term=boots&key=<my_key_inserted_here>
码:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://api.zappos.com/Search");
NameValuePair keypair = new BasicNameValuePair("key",KEY);
NameValuePair termpair = new BasicNameValuePair("term",data);
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(keypair);
params.add(termpair);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity =response.getEntity();
if (entity != null) {
DataInputStream in = new DataInputStream(entity.getContent());
while (( str = in.readLine()) != null){
sb.append(str);
}
in.close();
}
Log.i("serverInterface","response from server is :"+sb.toString());
我究竟做错了什么?
最佳答案
如果我是正确的话,您想要做的是带有参数的GET请求。
然后,代码看起来像这样:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://api.zappos.com/Search");
HttpParams params = new BasicHttpParams();
params.setParameter("key", "KEY");
params.setParameter("term", "data");
get.setParams(params);
HttpResponse response;
response = client.execute(get);
String str;
StringBuilder sb = new StringBuilder();
HttpEntity entity = response.getEntity();
if (entity != null) {
DataInputStream in;
in = new DataInputStream(entity.getContent());
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
}
Log.i("serverInterface", "response from server is :" + sb.toString());