failcz.msebera.android.httpclient.client.httpresponseexcepti



我正在使用'com.loopj.android:android-async-http:1.4.9'库,并尝试从以下URL http://api接收天气数据JSON对象.openweathermap.org/data/2.5/天气由于安全原因,隐藏了API密钥。

公共类WeatherController扩展了AppCompatactivity {

// Constants:
final int REQUEST_CODE = 123;
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
// App ID to use OpenWeather data
final String APP_ID = "e****************************a";
// Time between location updates (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
// Distance between location updates (1000m or 1km)
final float MIN_DISTANCE = 1000;
// TODO: Set LOCATION_PROVIDER here:
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;

// Member Variables:
TextView mCityLabel;
ImageView mWeatherImage;
TextView mTemperatureLabel;
// TODO: Declare a LocationManager and a LocationListener here:
LocationManager mLocationManager; // start or stop requesting location updates
LocationListener mLocationListener;// it will be notified is the location is actually changed

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.weather_controller_layout);
    // Linking the elements in the layout to Java code
    mCityLabel = (TextView) findViewById(R.id.locationTV);
    mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
    mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
    ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);

    // TODO: Add an OnClickListener to the changeCityButton here:
}

// TODO: Add onResume() here:
@Override
protected void onResume() {
    super.onResume();
    Log.d("clima", "onResume() called");
    Log.d("clima", "gettin weather for current location");
    getWeatherForCurrentLocation();

}

// TODO: Add getWeatherForNewCity(String city) here:

// TODO: Add getWeatherForCurrentLocation() here:
private void getWeatherForCurrentLocation() {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d("clima", "onLocationChnaged() callback recieved");
           String longitude = String.valueOf(location.getLongitude());
           String latitude = String.valueOf(location.getLatitude());
           Log.d("clima","longitude is"+longitude);
            Log.d("clima","latitude is"+latitude);
            RequestParams params = new RequestParams();
            params.put("lat",latitude);
            params.put(",lon",longitude);
            params.put("appid",APP_ID);
            letsDoSomeNetworking(params);
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("clima", "onProviderDisabled() callback recievd");

        }
    };
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
        return;
    }
    mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CODE) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d("clima", "onRequestPermissionsResult() : Permission granted");
            getWeatherForCurrentLocation();
        } else {
            Log.d("clima", "permission denied");
        }

    }

}

//todo:添加letsdosomenetworking(requestParams params(:

private void letsDoSomeNetworking(RequestParams params){
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(WEATHER_URL,params, new JsonHttpResponseHandler(){

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response){
            Log.d("clima","Success! JSON"+response.toString());
        }
        public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject response){
            Log.d("clima","Fail"+e.toString());
            Log.d("clima","status code"+statusCode);
            Toast.makeText(WeatherController.this,"Request Failed",Toast.LENGTH_SHORT).show();

        }

尝试添加JSON对象并获取msebera.android.httpclient.client.httpresponseexception:不良请求和状态为Code400,这是不成功的请求

您的代码:

params.put(",lon",longitude);

看起来像是错字错误,因为括号内有两个逗号,请删除报价中的第一个逗号。

修复了这两行代码

final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";    
final String APP_ID = "e****************************a";

在第一行中,您在API呼叫的基本URL之后没有任何内容,您需要附加:

?lat=-122.5564&lon=37.1516&appid=e****************************a

,您将在开放天气下注册,因为您要建立天气应用程序

第二行放置您的APP_ID

最新更新