简体   繁体   中英

Failcz.msebera.android.httpclient.client.HttpResponseException: Bad Request error while making HTTP request for weather app

I am using 'com.loopj.android:android-async-http:1.4.9' Library and trying to receive the weather data JSON object from the following URL http://api.openweathermap.org/data/2.5/weather and API key is hidden due to security reasons.

public class WeatherController extends 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: Add letsDoSomeNetworking(RequestParams params) here:

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();



        }

Trying to acess the JSON Object and getting msebera.android.httpclient.client.HttpResponseException: Bad Request and status as code400, which is for unsuccessful request attempt

Your code:

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

Looks like a typo error, because there are two commas inside the parentheses, remove the first comma inside the quote.

Fix these 2 lines of codes

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

In the 1st line, you don't have anything after Base URL for API Calls, you need to append:

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

and you'll get your app ID by signing up at open weather since you are building a weather app

for the 2nd line put your APP_ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM