改造 400 个错误请求

问题描述 投票:0回答:3

这是我用于网络调用的函数。

private void getSample() {


    Log.d("", "getSample : ");
    OkHttpClient client = new OkHttpClient();

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(NetworkCalls.BASE_URL)
            .client(client)

            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    NetworkCalls.CustomerApi customerApi = retrofit.create(NetworkCalls.CustomerApi.class);

    Log.e("customerApi  Created", "customerApi object Created : ");

    customerApi.getCategories("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjgsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMS42MDo4ODg4XC9DQ1YzXC9wdWJsaWNcL2FwaVwvbG9naW4iLCJpYXQiOjE0NDk0ODg5NDMsImV4cCI6MTQ0OTQ5MjU0MywibmJmIjoxNDQ5NDg4OTQzLCJqdGkiOiI0ODY4ZmNmZDk4OTIxZGQwYjA2ZDZlN2EyYjRjZGMxMSJ9.7c60LRQMFCtqprCbbULgR5xG-FxwXnRUZPuWeMJXcNE")
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Response<DataCategoryList>>() {
                @Override
                public void onCompleted() {

                    Log.e("onCompleted", "onCompleted : ");

                }

                @Override
                public void onError(Throwable e) {
                    Log.e("onError", "onError : " + e.getMessage());
                    e.printStackTrace();

                    // network errors, e. g. UnknownHostException, will end up here
                }

                @Override
                public void onNext(Response<DataCategoryList> startupResponseResponse) {



                }
            });
}

接口类

public interface CustomerApi {
    @Headers({
            "Accept: application/json"
    })
    @FormUrlEncoded
    @POST("categories")
    Observable<Response<DataCategoryList>> getCategories(@Field("token") String token);

    }

收到 400 错误请求。

错误日志

  <-- HTTP/1.1 400 Bad Request (207ms)
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Date: Mon, 07 Dec 2015 12:19:22 GMT
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Server: Apache/2.2.29 (Unix) mod_wsgi/3.5 Python/2.7.10 PHP/5.6.10 mod_ssl/2.2.29 OpenSSL/0.9.8zg DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.22.0
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: X-Powered-By: PHP/5.6.10
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Cache-Control: no-cache
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Set-Cookie: XSRF-TOKEN=5Uqd6WSjbalLcvX3o9RLDY1bGt69ktNoiLZZOahP; expires=Mon, 07-Dec-2015 14:19:22 GMT; Max-Age=7200; path=/
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Set-Cookie: laravel_session=882b5bdedd5dac0fcbfb88706406e3cc0acf91f6; expires=Mon, 07-Dec-2015 14:19:22 GMT; Max-Age=7200; path=/; httponly
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Content-Length: 30
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Connection: close
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: Content-Type: application/json
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: OkHttp-Selected-Protocol: http/1.1
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: OkHttp-Sent-Millis: 1449490736233
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: OkHttp-Received-Millis: 1449490736410
  12-07 17:48:56.408 21024-21067/com.cc.customer D/OkHttp: <-- END HTTP (30-byte body)

任何帮助将不胜感激。

android retrofit
3个回答
26
投票

400 听起来像是您从服务器收到的特定错误代码。 您可以通过在Retrofit上添加日志级别来尝试调试。

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
clientBuilder.addInterceptor(loggingInterceptor);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(NetworkCalls.BASE_URL)
        .client(clientBuilder.build())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build();

将依赖项添加到gradle

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

使用日志级别,您可能会看到从服务器返回的一些错误 json。

示例:

 {"statusCode":400,"message":"Some parameters are missing"}
 D/Retrofit: <--- END HTTP (76-byte body)

7
投票

我在地图中发送数据后解决了我的问题。它对我有用。

     Map<String,String> hashMap=new HashMap<>();
    hashMap.put("client_id","2");
    hashMap.put("client_secret",Constant.CLIENT_SECRET);
    hashMap.put("grant_type",Constant.GRANT_TYPE);
    hashMap.put("username",et_user.getText.toString();
    hashMap.put("password",etpassword.getText().toString());
    Call<LoginDataModel> call=apiInterface.login(hashMap);

在 ApiInterface 中我只是添加了这样的方法

 @FormUrlEncoded
@POST("oauth/token")
Call<LoginDataModel> login(@FieldMap Map<String, String> options);

0
投票

要处理响应中的 400 Bad Request 错误,请使用以下代码。

         if (response.isSuccessful()) {
            if (response.body().getStatus().equals(1)) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(UploadPDFActivity.this, "Success", 
        Toast.LENGTH_SHORT).show();
            }
        } else {
            int statusCode = response.code();
            Log.e("hello 4001", "else condition");

            if (statusCode == 400) {
                progressBar.setVisibility(View.GONE);
                if (!response.isSuccessful()) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response.errorBody().string());
                        String entityId = jsonObject.getString("entity_id");
                        String errorMessage = jsonObject.getString("message");
                        String errorStatus = jsonObject.getString("status");
                        Log.e("hello entityId", entityId);
                        Log.e("hello errorMessage", errorMessage);
                        Log.e("hello errorStatus", errorStatus);
                        Toast.makeText(UploadPDFActivity.this, errorMessage, Toast.LENGTH_SHORT).show();

                    } catch (JSONException | IOException e) {
                        e.printStackTrace();
                    }
                }

                 }
                  else {
                // Handle other error cases
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.