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

标签 java android json loopj

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

公共(public)类 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();



        }

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

最佳答案

您的代码:

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

看起来是打字错误,因为括号里面有两个逗号,去掉引号里面的第一个逗号。

关于java - Failcz.msebera.android.httpclient.client.HttpResponseException : Bad Request error while making HTTP request for weather app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736977/

相关文章:

java - 在java中创建一个通用对象并使用它来创建另一个通用对象

java - 比较输入文件列表中的数字

android - 我们如何在 Android Jetpack Compose UI 中将文本格式化为上标或下标?

android - 包含的 xml 布局的访问 View

javascript - 在加载函数外部访问变量

php - JSON - 如何在 php 中合并数组内的嵌套对象

java - 空指针异常。无法读取流

java - 在不使用 Maven 的情况下在 NetBeans 上使用 Vaadin

sql - 读取 JSON 数组作为 SQL 表列之一

json - 嵌套的 for-in 循环搜索 JSON 数据以匹配字符串 Swift