我正在尝试从Google Places API获取数据。但是,我的代码中的问题是我根本没有从HTTP客户端获取任何数据。
我在文本框中看不到什么都看不到(应该从Google API获得响应)
Java文件代码:
public class Httpexample extends Activity implements OnClickListener{
TextView tv_ResponseAPI;
Button btn_GetResponse;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.api_example);
tv_ResponseAPI = (TextView) findViewById(R.id.tv_ResponseAPI);
btn_GetResponse = (Button) findViewById(R.id.btn_GetResponse);
btn_GetResponse.setOnClickListener(this);
Log.v("Http", "entered the onCreate function");
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_GetResponse:
Log.v("Http", "Button was clicked");
//tv_ResponseAPI.setText("Button was clicked");
getInternetdata();
break;
default:
break;
}
}
public void getInternetdata() {
Log.v("Http", "Entered getInternetData()");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=my_api_here");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream webs = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
tv_ResponseAPI.setText(reader.readLine());
webs.close();
} catch(Exception e) {
Log.e("log_tab", "Error Converting Result :" + e.toString());
}
} catch (Exception e) {
Log.e("log_tab", "Error in http connection :" + e.toString());
}
}
}
即使我的API密钥(我已经检查过的)或某些东西搞砸了,我应该像以下内容一样得到JSON格式响应?我什么都没有。提出断点和调试,编程冻结并在"响应"语句之前什么都不做。
httpget(" ...")中的URL是这里的示例:https://developers.google.com/places/documentation/search
{
"html_attributions": [],
"results": [],
"status": "REQUEST_DENIED"
}
我能够使用asynctask解决问题。由于我的API级别> 3.0,我认为我需要使用它。
我在以下链接上遵循了代码示例,作为ping google ploces api的指南:http://hmkcode.com/android-introid-intreid-internet-connection-usish-usis-http-get-httpclient/plient/plient/ptpclient/ptpclient/p>