Search in sources :

Example 1 with MediaType

use of com.squareup.okhttp.MediaType in project bdcodehelper by boredream.

the class ErrorConstants method parseHttpErrorInfo.

/**
     * 解析服务器错误信息
     */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                ErrorResponse errorResponse = new Gson().fromJson(responseBody.string(), ErrorResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : UnknownHostException(java.net.UnknownHostException) MediaType(com.squareup.okhttp.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit.HttpException) UnknownHostException(java.net.UnknownHostException) HttpException(retrofit.HttpException) ResponseBody(com.squareup.okhttp.ResponseBody) ErrorResponse(com.boredream.bdcodehelper.entity.ErrorResponse)

Example 2 with MediaType

use of com.squareup.okhttp.MediaType in project xDrip by NightscoutFoundation.

the class ShareRest method getOkHttpClient.

private synchronized OkHttpClient getOkHttpClient() {
    try {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                try {
                    // Add user-agent and relevant headers.
                    Request original = chain.request();
                    Request copy = original.newBuilder().build();
                    Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
                    Log.d(TAG, "Sending request: " + modifiedRequest.toString());
                    Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    Log.d(TAG, "Request body: " + buffer.readUtf8());
                    final Response response = chain.proceed(modifiedRequest);
                    Log.d(TAG, "Received response: " + response.toString());
                    if (response.body() != null) {
                        MediaType contentType = response.body().contentType();
                        String bodyString = response.body().string();
                        Log.d(TAG, "Response body: " + bodyString);
                        return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
                    } else
                        return response;
                } catch (NullPointerException e) {
                    Log.e(TAG, "Got null pointer exception: " + e);
                    return null;
                } catch (IllegalStateException e) {
                    UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
                    return null;
                }
            }
        });
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException("Error occurred initializing OkHttp: ", e);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 3 with MediaType

use of com.squareup.okhttp.MediaType in project xDrip-plus by jamorham.

the class ShareRest method getOkHttpClient.

private synchronized OkHttpClient getOkHttpClient() {
    try {
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.networkInterceptors().add(new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                try {
                    // Add user-agent and relevant headers.
                    Request original = chain.request();
                    Request copy = original.newBuilder().build();
                    Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
                    Log.d(TAG, "Sending request: " + modifiedRequest.toString());
                    Buffer buffer = new Buffer();
                    copy.body().writeTo(buffer);
                    Log.d(TAG, "Request body: " + buffer.readUtf8());
                    final Response response = chain.proceed(modifiedRequest);
                    Log.d(TAG, "Received response: " + response.toString());
                    if (response.body() != null) {
                        MediaType contentType = response.body().contentType();
                        String bodyString = response.body().string();
                        Log.d(TAG, "Response body: " + bodyString);
                        return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
                    } else
                        return response;
                } catch (NullPointerException e) {
                    Log.e(TAG, "Got null pointer exception: " + e);
                    return null;
                } catch (IllegalStateException e) {
                    UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
                    return null;
                }
            }
        });
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException("Error occurred initializing OkHttp: ", e);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 4 with MediaType

use of com.squareup.okhttp.MediaType in project stetho by facebook.

the class StethoInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = mEventReporter.nextRequestId();
    Request request = chain.request();
    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request, requestBodyHelper);
        mEventReporter.requestWillBeSent(inspectorRequest);
    }
    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }
    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }
        Connection connection = chain.connection();
        if (connection == null) {
            throw new IllegalStateException("No connection associated with this request; " + "did you use addInterceptor instead of addNetworkInterceptor?");
        }
        mEventReporter.responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));
        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }
        responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }
    return response;
}
Also used : InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) Connection(com.squareup.okhttp.Connection) IOException(java.io.IOException) DefaultResponseHandler(com.facebook.stetho.inspector.network.DefaultResponseHandler) ResponseBody(com.squareup.okhttp.ResponseBody) Response(com.squareup.okhttp.Response) RequestBodyHelper(com.facebook.stetho.inspector.network.RequestBodyHelper) MediaType(com.squareup.okhttp.MediaType)

Example 5 with MediaType

use of com.squareup.okhttp.MediaType in project bdcodehelper by boredream.

the class ErrorInfoUtils method parseHttpErrorInfo.

/**
     * 解析服务器错误信息
     */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                ErrorResponse errorResponse = new Gson().fromJson(responseBody.string(), ErrorResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : UnknownHostException(java.net.UnknownHostException) MediaType(com.squareup.okhttp.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit.HttpException) UnknownHostException(java.net.UnknownHostException) HttpException(retrofit.HttpException) ResponseBody(com.squareup.okhttp.ResponseBody) ErrorResponse(com.boredream.bdcodehelper.entity.ErrorResponse)

Aggregations

MediaType (com.squareup.okhttp.MediaType)9 Request (com.squareup.okhttp.Request)5 Response (com.squareup.okhttp.Response)5 IOException (java.io.IOException)5 ResponseBody (com.squareup.okhttp.ResponseBody)3 ErrorResponse (com.boredream.bdcodehelper.entity.ErrorResponse)2 Gson (com.google.gson.Gson)2 Connection (com.squareup.okhttp.Connection)2 Headers (com.squareup.okhttp.Headers)2 Interceptor (com.squareup.okhttp.Interceptor)2 MultipartBuilder (com.squareup.okhttp.MultipartBuilder)2 OkHttpClient (com.squareup.okhttp.OkHttpClient)2 RequestBody (com.squareup.okhttp.RequestBody)2 File (java.io.File)2 UnknownHostException (java.net.UnknownHostException)2 CertificateException (java.security.cert.CertificateException)2 ExecutionException (java.util.concurrent.ExecutionException)2 HostnameVerifier (javax.net.ssl.HostnameVerifier)2 SSLContext (javax.net.ssl.SSLContext)2 SSLSession (javax.net.ssl.SSLSession)2