发送HTTP请求会引发异常(预期':状态'标头不存在)?

时间:2018-01-03 16:46:26

标签: java android wordpress retrofit okhttp

当我尝试发送HTTP请求时,会抛出错误(预期':status'标头不存在)。

我在3天后创建了这段代码并且运行良好,但是现在我尝试运行我的应用程序给了我这个

我不知道它与服务器或WordPress网站有关吗?

错误:

 W/System.err:     at rx.Observable$2.call(Observable.java:162)
    W/System.err:     at rx.Observable$2.call(Observable.java:154)
    W/System.err:     at rx.Observable$2.call(Observable.java:162)
    W/System.err:     at rx.Observable$2.call(Observable.java:154)
    W/System.err:     at rx.Observable.unsafeSubscribe(Observable.java:7710)
    W/System.err:     at rx.internal.operators.OperatorSubscribeOn$1$1.call(OperatorSubscribeOn.java:62)
    W/System.err:     at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
    W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
    W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    W/System.err:     at java.lang.Thread.run(Thread.java:761)
    E/HomeActivity: categories Error Expected ':status' header not present...
    W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

// interface calss

package com.hgomy.android.hdomy.data.api;
import com.hgomy.android.hdomy.data.callback.StoreCallback;
import com.hgomy.android.hdomy.models.Category;
import com.hgomy.android.hdomy.models.Data;
import com.hgomy.android.hdomy.models.Review;
import com.hgomy.android.hdomy.models.customer;
import com.hgomy.android.hdomy.models.products;
import java.util.List;
import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.http.Url;
import rx.Observable;

public interface woocommerce
{
    String WC_API_VERSION = "1";
  String consumer_key = "***************************"; // Add your own Consumer Key here
    String consumer_secret = "**************************"; // Add your own Consumer Secret here
    String BASE_URL = "https://hdomy.tk/wp-json/wc/v" + WC_API_VERSION + "/" ;


    @GET
    Observable<StoreCallback> store(@Url String url);

    ////////////////////////////////////////////////////////////////////////
    //products
    ////////////////////////////////////////////////////////////////////////
    @Headers("Content-Type: application/json")
    @GET("products/categories")
    Observable<List<Category>> getCategories();

    @Headers("Content-Type: application/json")
    @GET
    Observable<List<Category>> getCategories2(@Url String url);

    @Headers("Content-Type: application/json")
    @GET("products")
    Observable<List<products>> getProducts();

     @Headers("Content-Type: application/json")
    @GET("products")
    Observable<List<products>> getProducts(@Query("category") int category);

    @GET("products")
    Observable<List<products>> getProducts2(@Query("category") int category, @Query("page") int page);

    @GET("products/{id}")
    Observable<products> getRelatedProducts(@Path("id") int id);

    @Headers("Content-Type: application/json")
    @GET("products/{id}")
    Observable<products> getProduct(@Path("id") int id);

    @Headers("Content-Type: application/json")
    @GET
    Observable<List<Review>> getProductReviews(@Url String url);

    @Headers("Content-Type: application/json")
    @POST("customers")
    Call<customer> registerUser(@Body customer body);

    @Headers("Content-Type: application/json")
    @POST("customers")
    Call<customer> registerUser2(@Body Data body);

    @GET
    Call<customer> loginUser(@Url String url);

    @GET("customers/email/{email}")
    Call<customer> loginUser2(@Path("email") String email);

     @Headers("Content-Type: application/json")
    @GET("customers")
    Call<List<customer>> getCustomer(@Query("email") String email);
}

// Rest Adapter

public class FullUrlRestAdapter {


    static ArrayList<NameValuePair> params;

    public static woocommerce createAPI(final String fullUrl) {

        Log.d("class", "FullUrlRestAdapter");
        Log.d("fullUrl", fullUrl);

        params = new ArrayList<>();
        setParams(fullUrl);

        // Define the interceptor, add authentication headers
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                HttpUrl.Builder builder = chain.request().httpUrl().newBuilder();
                for (NameValuePair entry : params) {
                    builder.addQueryParameter(entry.getName(), entry.getValue());
                }

                Request newRequest = chain.request()
                        .newBuilder()
                        .url(builder.build())
                        .header("Accept", "application/json")
                        .build();
                           Log.e("requesterror", "requesterror");

                return chain.proceed(newRequest);
            }
        };

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        client.interceptors().add(logging);
        client.interceptors().add(interceptor);

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

        return retrofit.create(woocommerce.class);
    }

    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    public static ArrayList<NameValuePair> setParams(String endpoint) {
        final String uri = woocommerce.BASE_URL + endpoint;


        params = new ArrayList<>();
        params.add(new BasicNameValuePair("consumer_key", woocommerce.consumer_key));
        params.add(new BasicNameValuePair("consumer_secret", woocommerce.consumer_secret));

        Collections.sort(params, new SortParams());

        String encodedParams = URLEncodedUtils.format(params, "utf-8");
        Log.d("full encodedParamString", encodedParams);

        String string_to_sign = "";
        try {
            string_to_sign = (new StringBuilder("GET&")).append(URLEncoder.encode(endpoint, "utf-8")).append("&").append(URLEncoder.encode(encodedParams, "utf-8")).toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Log.d("full string to sign", string_to_sign);

        return params;
    }

    static class SortParams implements Comparator<NameValuePair> {

        @Override
        public int compare(NameValuePair nameValuePair1, NameValuePair nameValuePair2) {
            return nameValuePair1.getName().compareTo(nameValuePair2.getName());
        }
    }
}

// Gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.hgomy.android.hdomy"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //square libraries
    compile('com.squareup.retrofit:retrofit:2.0.0-beta2') {
        exclude module: 'okhttp'
    }
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

    compile('com.mikepenz:materialdrawer:4.5.4@aar') {
        transitive = true
    }
    compile files('src/main/libs/org.apache.http.legacy.jar')

    //GCM
    compile 'com.android.support:appcompat-v7:25.4.0'
    compile 'com.android.support:design:25.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
    compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.colintmiller:simplenosql:0.5.1'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'com.github.frankiesardo:linearlistview:1.0.1@aar'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.maps.android:android-maps-utils:0.4'
    compile 'com.google.android.gms:play-services-maps:11.8.0'
    compile 'com.github.ViksaaSkool:AwesomeSplash:v1.0.0'
    compile 'io.reactivex:rxandroid:1.0.1'
   //compile 'com.squareup.retrofit:converter-jackson:2.0.0-beta2'
    //compile 'com.viewpagerindicator:library:2.4.1@aar.jar'
//    compile 'io.reactivex:rxjava:1.0.4'
    //compile 'com.github.bumptech.glide:glide:3.6.1'
//    compile 'uk.co.chrisjenx:calligraphy:2.1.0'
    compile 'com.github.frankiesardo:linearlistview:1.0.1@aar'

    testCompile 'junit:junit:4.12'
}

//获取数据的代码

private void getProductCategories() {
        String url = woocommerce.BASE_URL + "products/categories";
        woocommerce wooCommerceApi = FullUrlRestAdapter.createAPI(url);
        rx.Observable<List<Category>> productCallbackObservable = wooCommerceApi.getCategories2(url);
        productCallbackObservable
                .retry(2)
                .take(4)
                .observeOn(AndroidSchedulers.mainThread()).
                subscribeOn(Schedulers.newThread()).
                subscribe(new Subscriber<List<Category>>() {
                    @Override
                    public void onCompleted() {
                    }                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Log.e("HomeActivity", "categories Error " + e.getMessage() + "...");
                    }
                    @Override
                    public void onNext(List<Category> categories) {
                        Log.d("HomeActivity", "categories size " + categories.size() + "..");
                        if (categories.size() > 0) {

                            for (int i = 0; i < categories.size(); i++) {
//                                for (String aCategoriesToDisplay : categoriesToDisplay) {
//                                    if (categories.get(i).getName().equals(aCategoriesToDisplay)) {
//                                        setupCategories(categories.get(i));
//                                    }
//                                }
                                setupCategories(categories.get(i));
                            }

                        } else {
                            //TODO handle empty categories
                        }
                    }
                });
    }

//错误

E/HomeActivity: categories Error Expected ':status' header not present...

我在3天后创建了这段代码并且运行良好,但现在我尝试运行我的应用程序,这给了我这个错误。

1 个答案:

答案 0 :(得分:0)

只需将Retrofit和Okhttp3库更新到最新版本。

compile 'com.squareup.okhttp3:okhttp:3.9.0'

compile 'com.squareup.retrofit2:retrofit:2.3.0'