Search in sources :

Example 86 with Headers

use of okhttp3.Headers in project chefly_android by chef-ly.

the class HttpConnection method downloadFromFeed.

public String downloadFromFeed(RequestMethod requestPackage) throws IOException {
    String address = requestPackage.getEndpoint();
    String encodedParams = requestPackage.getEncodedParams();
    //check for get request
    if (requestPackage.getMethod().equals("GET") && encodedParams.length() > 0) {
        address = String.format("%s?%s", address, encodedParams);
    }
    //create request object
    OkHttpClient client;
    if (BuildConfig.DEBUG) {
        client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
    } else {
        client = new OkHttpClient();
    }
    Request.Builder requestBuilder = new Request.Builder().url(address);
    //  Add required HTTP Header
    Map<String, String> headers = requestPackage.getHeaders();
    if (headers.size() > 0) {
        for (String k : headers.keySet()) {
            if (k != null) {
                requestBuilder.addHeader(k, headers.get(k));
            }
        }
    }
    //check for post request
    if (requestPackage.getMethod().equals("POST")) {
        //extract the parameters from the request
        //get the reference of the pair
        Map<String, String> params = requestPackage.getParams();
        String msg = "";
        if (params.size() == 1) {
            for (String key : params.keySet()) msg = params.get(key);
        } else {
            JSONObject parameter = new JSONObject(params);
            msg = parameter.toString();
        }
        RequestBody body = RequestBody.create(JSON, msg);
        Log.d(TAG, msg);
        requestBuilder.post(body);
        //requestBuilder.addHeader("content-type", "application/json; charset=utf-8");
        requestBuilder.addHeader("content-type", "application/x-www-form-urlencoded");
    }
    Request request = requestBuilder.build();
    //get response with the use of the method newCall
    //synchronous request
    Response response = client.newCall(request).execute();
    //check if the request is successful
    if (response.isSuccessful()) {
        this.statusMessage = response.message();
        return response.body().string();
    } else {
        Log.d(TAG, response.toString());
        throw new IOException("Exception: response code " + response.code());
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 87 with Headers

use of okhttp3.Headers in project smartmodule by carozhu.

the class ReceivedCookiesInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Response originalResponse = chain.proceed(chain.request());
    //这里获取请求返回的cookie
    if (!originalResponse.headers("Set-Cookie").isEmpty()) {
        final StringBuffer cookieBuffer = new StringBuffer();
        //这里用了RxJava的相关API大家可以忽略,用自己逻辑实现即可.大家可以用别的方法保存cookie数据
        Observable.from(originalResponse.headers("Set-Cookie")).map(new Func1<String, String>() {

            @Override
            public String call(String s) {
                String[] cookieArray = s.split(";");
                return cookieArray[0];
            }
        }).subscribe(new Action1<String>() {

            @Override
            public void call(String cookie) {
                cookieBuffer.append(cookie).append(";");
            }
        });
        SharedPreferences sharedPreferences = mcontext.getSharedPreferences("cookie", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String[] sessionArry = cookieBuffer.toString().split("=");
        editor.putString("cookie", sessionArry[1]);
        editor.commit();
        Log.d("ReceivedCookiesIntec", "get cookie ------->:" + sessionArry[1]);
    } else {
        Log.d("ReceivedCookiesIntec", "headers Set-Cookie.isEmpty()");
    }
    return originalResponse;
}
Also used : Response(okhttp3.Response) SharedPreferences(android.content.SharedPreferences) Func1(rx.functions.Func1)

Example 88 with Headers

use of okhttp3.Headers in project openstack4j by ContainX.

the class KeystoneTokenlessTest method pass_headers_Test.

/**
     * check headers whether right from request
     *
     * @throws Exception
     */
public void pass_headers_Test() throws Exception {
    respondWith(JSON_USERS);
    OSClient.OSClientV3 osClient = OSFactory.builderV3().endpoint(authURL("/v3")).scopeToDomain(Identifier.byId(DOMAIN_ID)).authenticate();
    osClient.identity().users().list();
    RecordedRequest request = server.takeRequest();
    assertEquals(request.getHeader(ClientConstants.HEADER_X_DOMAIN_ID), DOMAIN_ID);
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) OSClient(org.openstack4j.api.OSClient)

Example 89 with Headers

use of okhttp3.Headers in project Retrofit-Android-Basic by basil2style.

the class ServiceGenerator method createService.

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    if (authToken != null) {
        httpClient.interceptors().add(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken).method(original.method(), original.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
    }
    OkHttpClient client = httpClient.build();
    Retrofit retrofit = builder.client(client).build();
    return retrofit.create(serviceClass);
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 90 with Headers

use of okhttp3.Headers in project Varis-Android by dkhmelenko.

the class BuildsDetailsPresenter method startLoadingLog.

/**
     * Starts loading log file
     *
     * @param jobId Job ID
     */
public void startLoadingLog(long jobId) {
    mJobId = jobId;
    String accessToken = AppSettings.getAccessToken();
    Single<String> responseSingle;
    if (TextUtils.isEmpty(accessToken)) {
        responseSingle = mRawClient.getApiService().getLog(String.valueOf(mJobId));
    } else {
        String auth = String.format("token %1$s", AppSettings.getAccessToken());
        responseSingle = mRawClient.getApiService().getLog(auth, String.valueOf(mJobId));
    }
    Disposable subscription = responseSingle.subscribeOn(Schedulers.io()).map(s -> mRawClient.getLogUrl(mJobId)).onErrorResumeNext(new Function<Throwable, SingleSource<String>>() {

        @Override
        public SingleSource<String> apply(@NonNull Throwable throwable) throws Exception {
            String redirectUrl = "";
            HttpException httpException = (HttpException) throwable;
            Headers headers = httpException.response().headers();
            for (String header : headers.names()) {
                if (header.equals("Location")) {
                    redirectUrl = headers.get(header);
                    break;
                }
            }
            return Single.just(redirectUrl);
        }
    }).retry(LOAD_LOG_MAX_ATTEMPT).observeOn(AndroidSchedulers.mainThread()).subscribe((logUrl, throwable) -> {
        if (throwable == null) {
            getView().setLogUrl(logUrl);
        } else {
            getView().showLogError();
            getView().showLoadingError(throwable.getMessage());
        }
    });
    mSubscriptions.add(subscription);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Function(io.reactivex.functions.Function) Headers(okhttp3.Headers) NonNull(io.reactivex.annotations.NonNull) HttpException(retrofit2.HttpException)

Aggregations

Test (org.junit.Test)69 Request (okhttp3.Request)58 Response (okhttp3.Response)53 Headers (okhttp3.Headers)46 IOException (java.io.IOException)34 MockResponse (okhttp3.mockwebserver.MockResponse)33 HttpHeaders (okhttp3.internal.http.HttpHeaders)29 ResponseBody (okhttp3.ResponseBody)27 RequestBody (okhttp3.RequestBody)21 List (java.util.List)19 MediaType (okhttp3.MediaType)16 HashMap (java.util.HashMap)15 Map (java.util.Map)15 ANResponse (com.androidnetworking.common.ANResponse)13 AnalyticsListener (com.androidnetworking.interfaces.AnalyticsListener)13 LinkedHashMap (java.util.LinkedHashMap)13 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Buffer (okio.Buffer)12 ANError (com.androidnetworking.error.ANError)11 HttpURLConnection (java.net.HttpURLConnection)11