【问题标题】:BasicNetwork.performRequest: Unexpected response code 400 in androidBasicNetwork.performRequest:android中的意外响应代码400
【发布时间】:2017-07-29 19:19:14
【问题描述】:

我正在尝试构建一个应用程序,在其中我使用JSON 来获取当前的latitudelongitude 以及address,但只要我点击button,我就会得到一个我的日志中的错误:

E/Volley:[5807] BasicNetwork.performRequest:https://maps.googleapis.com/maps/api/geocode/json?latlng=0.00.0 的意外响应代码 400

代码如下:

Gps3Activity.java

    public class Gps3Activity extends AppCompatActivity {
    private Button display;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private RequestQueue requestQueue;
    private double lat;
    private double lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps3);

        display = (Button) findViewById(R.id.displayL);
        requestQueue = Volley.newRequestQueue(this);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new myLocationlistener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);

        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Log.e("Latitude", String.valueOf(lat));
                Log.e("Longitude", String.valueOf(lng));

                JsonObjectRequest request = new JsonObjectRequest("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true", new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                            //textViewCity.setText(address);
                            Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(request);
            }
        });
    }

    private class myLocationlistener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    }
}

logcat

07-30 01:18:33.287 9750-9750/com.example.shaloin.gps2 W/System.err: org.json.JSONException: Index 0 out of range [0..0)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at org.json.JSONArray.get(JSONArray.java:293)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at org.json.JSONArray.getJSONObject(JSONArray.java:521)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at com.example.shaloin.gps2.Gps3Activity$1$1.onResponse(Gps3Activity.java:63)
07-30 01:18:33.288 9750-9750/com.example.shaloin.gps2 W/System.err:     at com.example.shaloin.gps2.Gps3Activity$1$1.onResponse(Gps3Activity.java:58)

我也无法弄清楚为什么我将latitudelongitude 的值设为0.0

谁能帮忙?谢谢你:)

【问题讨论】:

    标签: android json android-volley android-gps


    【解决方案1】:

    那里似乎有3个问题:

    第一:

    JsonObjectRequest() 的格式似乎完全错误。正确的格式是:

    JsonObjectRequest(int method,
                      String url,
                      JSONObject jsonRequest,
                      Response.Listener<JSONObject> listener,
                      Response.ErrorListener errorListener)
    

    参考thisthis

    第二:您收到来自 geocode API 的意外响应

    要使用 google 的地理编码 API,您必须先获取 API 密钥。 格式应该是这样的:(参考this文档)

    https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&location_type=ROOFTOP&result_type=street_address&key=YOUR_API_KEY
    

    所以你可以看到,它需要 API 密钥。您可以阅读here 以获取密钥。另外注意在纬度值和经度值之间有一个逗号 (,)。您的代码缺少这一点。

    第三:你得到latlng为0.0

    这是因为获取位置数据需要时间。操作系统不会调用onLocationChange(),直到它具有一定精度的位置数据。因此,当您单击该按钮时,直到那时您还没有更新位置。您应该做的是,当用户单击按钮时,向他显示带有消息 updating location 的进度条,并且仅在调用 onLocationChange() 时将其关闭。仅当至少调用一次“onLocationChange()”时才使用latlng

    【讨论】:

    • 我在制作应用程序时一直在关注stackoverflow.com/questions/20238197/…,正如您所说的 api key ,帖子中接受的答案没有它。
    • 选择权在你,如果你想按照 3 岁的回答去。用户可能认为它是“隐式”的,或者相信这些 google docs,这些 API 的所有者
    • 好的,正如你所说,我错过了昏迷,我修复了这个问题,现在日志显示如下:W/System.err: org.json.JSONException: Index 0 out of range [0..0)
    • 我已经更新了代码,还显示了logcat
    • 更新了答案
    【解决方案2】:

    我只需要更改JsonObjectRequest() 的格式。正如@ZeekHuge 所建议的,下面给出了正确的格式

    JsonObjectRequest(int method,
                  String url,
                  JSONObject jsonRequest,
                  Response.Listener<JSONObject> listener,
                  Response.ErrorListener errorListener)
    

    正确的代码如下:

    public class Gps3Activity extends AppCompatActivity {
    
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
    private Button display;
    private TextView displayLocation;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private RequestQueue requestQueue;
    private double lat;
    private double lng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps3);
    
        display = (Button) findViewById(R.id.displayL);
        displayLocation=(TextView)findViewById(R.id.location1);
        requestQueue = Volley.newRequestQueue(this);
    
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationListener = new myLocationlistener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
    
        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                getLocation(lat,lng);
    
                Log.e("Latitude", String.valueOf(lat));
                Log.e("Longitude", String.valueOf(lng));
                Log.e("city",address);
                Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
                displayLocation.setText("City : "+address);
    }
        });
    }
    
    private class myLocationlistener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
                //Toast.makeText(getApplicationContext(),"Latitude: "+lat+"\nLongitude: "+lng,Toast.LENGTH_LONG).show();
                getLocation(lat,lng);
            }
        }
    
        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
    
        }
    
        @Override
        public void onProviderEnabled(String s) {
    
        }
    
        @Override
        public void onProviderDisabled(String s) {
    
        }
    }
    
    public void getLocation(double latitude,double longitude){
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ latitude+","+longitude +"&sensor=true",
                new Response.Listener<JSONObject>() {
    
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                            //textViewCity.setText(address);
                            //Toast.makeText(getApplicationContext(), "City : " + address, Toast.LENGTH_LONG);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        });
        requestQueue.add(request);
    }
    }
    

    虽然使用此方法显示location 需要花费大量时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多