在尝试搜索坐标时使用HttpResponse时获取异常

时间:2014-04-29 16:21:32

标签: android

我在Android上很新,我正在尝试搜索城市的坐标。我已经按照各种教程制作了下面的代码。问题在于,在执行了行" HttpResponse response = client.execute(request);"它直接跳到异常,真的不明白为什么。在过去两天里,我一直在努力解决这个问题。

我已添加清单文件,项目构建目标是Google API 4.2.2

public double[] searchCoordinate(String city) {

   double[] coordinates = new double[2];
   String petHTTP1 = "http://maps.googleapis.com/maps/api/geocode/json?address=";
   String petHTTP2 = "&sensor=false";
   String petHTTP = petHTTP1 + city + petHTTP2;

   try {

      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet();
      request.setURI(new URI(petHTTP));
      HttpResponse response = client.execute(request);
      BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      StringBuffer sb = new StringBuffer("");
      String line = "";
      while ((line = in.readLine()) != null){
          sb.append(line);
      }
      in.close();

      System.out.println(sb.toString());

      JSONObject jsonObject = new JSONObject(sb.toString());
      String resp = jsonObject.getString("status");
      if (resp.equals("OK")) {
          JSONArray array = jsonObject.getJSONArray("results");
          JSONObject item = array.getJSONObject(0);
          JSONObject point = item.getJSONObject("geometry").getJSONObject("location");
          coordinates[0] = point.getDouble("lat");
          coordinates[1] = point.getDouble("lng");
          System.out.println("Longitude: "+coordinates[0]+" - Latitude: "+coordinates[1]);

      } 

  }catch (Exception e)  {
      e.printStackTrace();      
  }

  return coordinates;

} 

1 个答案:

答案 0 :(得分:0)

Android有一个GeoCoder构建来做这些事情。虽然,有时它会失败,但回退到HTTP是有道理的。

在我对这个问题的回答中:Google Geocoder service is unavaliable (Coordinates to address)我在AsyncTask中添加了一个实现。

使用它:

new GetAddressPositionTask().excecute("someaddress");

然后在onPostExcecute中处理结果:

@Override
protected void onPostExecute(LatLng result) {
    // use the looked up location here
    super.onPostExecute(result);
}

要启用其他地方的解决方案,您需要添加一个回调接口,或者只是将GetAddressPositionTask添加为内部类,这样就可以在答案准备就绪时调用外部类的方法。

为了完整性,我在这里也添加了GetAddressPositionTask的代码:

private class GetAddressPositionTask extends
        AsyncTask<String, Integer, LatLng> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected LatLng doInBackground(String... plookupString) {

        String lookupString = plookupString[0];
        final String lookupStringUriencoded = Uri.encode(lookupString);
        LatLng position = null;

        // best effort zoom
        try {
            if (geocoder != null) {
                List<Address> addresses = geocoder.getFromLocationName(
                        lookupString, 1);
                if (addresses != null && !addresses.isEmpty()) {
                    Address first_address = addresses.get(0);
                    position = new LatLng(first_address.getLatitude(),
                            first_address.getLongitude());
                }
            } else {
                Log.e(TAG, "geocoder was null, is the module loaded? "
                        + isLoaded);
            }

        } catch (IOException e) {
            Log.e(TAG, "geocoder failed, moving on to HTTP");
        }
        // try HTTP lookup to the maps API
        if (position == null) {
            HttpGet httpGet = new HttpGet(
                    "http://maps.google.com/maps/api/geocode/json?address="
                            + lookupStringUriencoded + "&sensor=true");
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            StringBuilder stringBuilder = new StringBuilder();

            try {
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {
                // Log.d("MAPSAPI", stringBuilder.toString());

                jsonObject = new JSONObject(stringBuilder.toString());
                if (jsonObject.getString("status").equals("OK")) {
                    jsonObject = jsonObject.getJSONArray("results")
                            .getJSONObject(0);
                    jsonObject = jsonObject.getJSONObject("geometry");
                    jsonObject = jsonObject.getJSONObject("location");
                    String lat = jsonObject.getString("lat");
                    String lng = jsonObject.getString("lng");

                    // Log.d("MAPSAPI", "latlng " + lat + ", "
                    // + lng);

                    position = new LatLng(Double.valueOf(lat),
                            Double.valueOf(lng));
                }

            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
            }

        }
        return position;
    }

    @Override
    protected void onPostExecute(LatLng result) {
        super.onPostExecute(result);
    }

};