我无法使用httpget检索谷歌API数据

时间:2014-01-24 08:20:18

标签: android api google-api google-places-api http-get

我正在尝试从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"
}

1 个答案:

答案 0 :(得分:0)

我能够使用AsyncTask解决问题。自从我的API级别> 3.0,我想我需要使用它。

我按照以下链接中的代码示例作为ping Google Places API的指南:http://hmkcode.com/android-internet-connection-using-http-get-httpclient/