Search in sources :

Example 26 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project odysee-android by OdyseeTeam.

the class Comments method performRequest.

/**
 * Performs the request to Comment Server
 * @param commentServer Url where to direct the request
 * @param params JSON containing parameters to send to the server
 * @param method One of the available methods for comments
 * @return Response from the server
 * @throws IOException throwable from OkHttpClient execute()
 */
public static Response performRequest(String commentServer, JSONObject params, String method) throws IOException {
    final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    Map<String, Object> requestParams = new HashMap<>(4);
    requestParams.put("jsonrpc", "2.0");
    requestParams.put("id", 1);
    requestParams.put("method", method);
    requestParams.put("params", params);
    final String jsonString = Lbry.buildJsonParams(requestParams).toString();
    RequestBody requestBody = RequestBody.create(jsonString, JSON);
    Request commentCreateRequest = new Request.Builder().url(commentServer.concat("?m=").concat(method)).post(requestBody).build();
    OkHttpClient client = new OkHttpClient.Builder().writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
    return client.newCall(commentCreateRequest).execute();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HashMap(java.util.HashMap) Request(okhttp3.Request) MediaType(okhttp3.MediaType) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Example 27 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project pod-chat-android-sdk by FanapSoft.

the class PodDownloader method downloadFileFromPodSpace.

public static Call downloadFileFromPodSpace(ProgressHandler.IDownloadFile progressHandler, String token, int tokenIssuer, String fileHash, String fileServer, String fileName, File destinationFolder, IDownloaderError downloaderErrorInterface) {
    Retrofit retrofit = ProgressResponseBody.getDownloadRetrofit(fileServer, progressHandler);
    FileApi api = retrofit.create(FileApi.class);
    Call<ResponseBody> call = api.downloadPodSpaceFile(fileHash, token, tokenIssuer);
    final String[] downloadTempPath = new String[1];
    call.enqueue(new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            new Thread(() -> {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                File downloadTempFile = null;
                try {
                    if (!destinationFolder.exists()) {
                        boolean createFolder = destinationFolder.mkdirs();
                    }
                    downloadTempFile = new File(destinationFolder, fileName);
                    if (!downloadTempFile.exists()) {
                        boolean fileCreationResult = downloadTempFile.createNewFile();
                        if (!fileCreationResult) {
                            downloaderErrorInterface.errorOnWritingToFile();
                            return;
                        }
                    }
                    // keep path for cancel handling
                    downloadTempPath[0] = downloadTempFile.getPath();
                    if (response.body() != null && response.isSuccessful()) {
                        byte[] byteReader = new byte[4096];
                        inputStream = response.body().byteStream();
                        outputStream = new BufferedOutputStream(new FileOutputStream(downloadTempFile));
                        while (true) {
                            int read = inputStream.read(byteReader);
                            if (read == -1) {
                                // download finished
                                Log.i(TAG, "File has been downloaded");
                                MediaType mediaType = response.body().contentType();
                                String type = null;
                                String subType = "";
                                if (mediaType != null) {
                                    type = mediaType.type();
                                    subType = mediaType.subtype();
                                }
                                File downloadedFile = new File(destinationFolder, fileName + "." + subType);
                                boolean savingSuccess = downloadTempFile.renameTo(downloadedFile);
                                if (savingSuccess) {
                                    ChatResponse<ResultDownloadFile> chatResponse = generatePodSpaceDownloadResult(fileHash, downloadedFile);
                                    progressHandler.onFileReady(chatResponse);
                                // 
                                } else {
                                    downloaderErrorInterface.errorOnWritingToFile();
                                }
                                break;
                            }
                            outputStream.write(byteReader, 0, read);
                            outputStream.flush();
                        }
                    } else {
                        if (response.errorBody() != null) {
                            downloaderErrorInterface.errorUnknownException(response.errorBody().string());
                        } else {
                            downloaderErrorInterface.errorUnknownException(response.message());
                        }
                    }
                } catch (Exception e) {
                    if (call.isCanceled()) {
                        handleCancelDownload(downloadTempFile);
                        return;
                    }
                    Log.e(TAG, e.getMessage());
                    downloaderErrorInterface.errorUnknownException(e.getMessage());
                } finally {
                    try {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                        downloaderErrorInterface.errorUnknownException(e.getMessage());
                    }
                }
            }).start();
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            if (call.isCanceled()) {
                handleCancelDownload(new File(downloadTempPath[0]));
                return;
            }
            Log.d(TAG, "ERROR " + t.getMessage());
            call.cancel();
            downloaderErrorInterface.errorUnknownException(t.getMessage());
        }
    });
    return call;
}
Also used : InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) CursorIndexOutOfBoundsException(android.database.CursorIndexOutOfBoundsException) ProgressResponseBody(com.fanap.podchat.networking.ProgressResponseBody) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit) FileOutputStream(java.io.FileOutputStream) MediaType(okhttp3.MediaType) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) ResultDownloadFile(com.fanap.podchat.chat.file_manager.download_file.model.ResultDownloadFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) FileApi(com.fanap.podchat.networking.api.FileApi)

Example 28 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project AndroidFastDevFrame by linglongxin24.

the class RetrofitManager method getRequestBody.

private String getRequestBody(MultipartBody.Part part) {
    Class<?> personType = part.getClass();
    // 访问私有属性
    Field field = null;
    try {
        field = personType.getDeclaredField("body");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    field.setAccessible(true);
    try {
        RequestBody requestBody = (RequestBody) field.get(part);
        MediaType contentType = requestBody.contentType();
        if (contentType.type().equals("multipart")) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset UTF8 = Charset.forName("UTF-8");
            Charset charset = contentType.charset(UTF8);
            return buffer.readString(charset);
        } else if (contentType.type().equals("image")) {
            if (requestBody != null) {
                return convertFileSize(requestBody.contentLength());
            } else {
                return "0b";
            }
        // Class<?> requestBodyClass = requestBody.getClass();
        // 
        // //访问私有属性
        // Field fileRequestBodyClass = null;
        // try {
        // fileRequestBodyClass = requestBodyClass.getDeclaredField("file");
        // 
        // 
        // fileRequestBodyClass.setAccessible(true);
        // File file = (File) fileRequestBodyClass.get(requestBody);
        // Logger.d("file=" + file.getPath());
        // } catch (NoSuchFieldException e) {
        // e.printStackTrace();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
Also used : Buffer(okio.Buffer) Field(java.lang.reflect.Field) MediaType(okhttp3.MediaType) Charset(java.nio.charset.Charset) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 29 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project AndroidFastDevFrame by linglongxin24.

the class RetrofitManager method initRetrofit.

public <T> void initRetrofit(Class<T> apiService, String baseUrl) {
    mOkHttpClient = new OkHttpClient();
    /**
     * 公共参数拦截器
     */
    Interceptor commParamsIntInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder();
            // 请求体定制:统一添加sign参数
            if (original.body() instanceof FormBody) {
                FormBody.Builder newFormBody = new FormBody.Builder();
                FormBody oidFormBody = (FormBody) original.body();
                String appName = "";
                String className = "";
                for (int i = 0; i < oidFormBody.size(); i++) {
                    String name = oidFormBody.encodedName(i);
                    String value = oidFormBody.encodedValue(i);
                    if ("app".equals(name)) {
                        appName = value;
                    } else if ("class".equals(name)) {
                        className = value;
                    }
                    newFormBody.addEncoded(name, value);
                }
                if (!TextUtils.isEmpty(appName) && !TextUtils.isEmpty(className) && !TextUtils.isEmpty(secret)) {
                    newFormBody.add("sign", MD5Utils.md5(appName + className + secret));
                    requestBuilder.method(original.method(), newFormBody.build());
                }
            }
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };
    /**
     * http请求日志拦截器
     */
    Interceptor httpInterceptor = new Interceptor() {

        private StringBuilder mMessage = new StringBuilder();

        @Override
        public Response intercept(Chain chain) throws IOException {
            mMessage.setLength(0);
            Request original = chain.request();
            mMessage.append("请求地址:");
            mMessage.append(original.url());
            mMessage.append("\n");
            Request.Builder requestBuilder = original.newBuilder();
            Request request = requestBuilder.build();
            Response response = chain.proceed(request);
            if ("POST".equals(original.method())) {
                mMessage.append("请求参数:");
                addRequestParement(original);
                mMessage.append("\n");
                mMessage.append("请求大小:");
                if (original.body() != null) {
                    mMessage.append(convertFileSize(original.body().contentLength()));
                }
                Logger.d(mMessage.toString());
                mMessage.setLength(0);
                mMessage.append("响应地址:");
                mMessage.append(response.request().url());
                mMessage.append("\n");
                mMessage.append("响应参数:");
                addRequestParement(response.request());
                mMessage.append("\n");
            }
            mMessage.append("响应耗时:");
            mMessage.append(formatDuring(response.receivedResponseAtMillis() - response.sentRequestAtMillis()));
            mMessage.append("\n");
            String content = response.body().string();
            okhttp3.MediaType mediaType = response.body().contentType();
            Response responseNew = response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
            mMessage.append("响应大小:");
            if (original.body() != null) {
                mMessage.append(convertFileSize(responseNew.body().contentLength()));
            }
            mMessage.append("\n");
            mMessage.append("响应数据:");
            mMessage.append("\n");
            mMessage.append(JsonParse.formatJson(EncodeUtils.ascii2native(content)));
            Logger.d(mMessage.toString());
            return responseNew;
        }

        private void addRequestParement(Request original) {
            // 请求体定制:统一添加sign参数
            if (original.body() instanceof FormBody) {
                // FormBody.Builder newFormBody = new FormBody.Builder();
                FormBody oidFormBody = (FormBody) original.body();
                for (int i = 0; i < oidFormBody.size(); i++) {
                    String name = oidFormBody.encodedName(i);
                    String value = oidFormBody.value(i);
                    // newFormBody.addEncoded(name, value);
                    if (mMessage.indexOf("=") != -1) {
                        mMessage.append("\n");
                        mMessage.append("     ");
                    }
                    mMessage.append(name);
                    mMessage.append("=");
                    mMessage.append(value);
                }
            } else if (original.body() instanceof MultipartBody) {
                MultipartBody multipartBody = (MultipartBody) original.body();
                for (MultipartBody.Part part : multipartBody.parts()) {
                    String name = getPartHeaders(part);
                    String value = null;
                    try {
                        value = URLDecoder.decode(getRequestBody(part).replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    // newFormBody.addEncoded(name, value);
                    if (mMessage.indexOf("=") != -1) {
                        mMessage.append("\n");
                        mMessage.append("     ");
                    }
                    mMessage.append(name);
                    mMessage.append("=");
                    mMessage.append(value);
                }
            }
        }
    };
    okhttpBuilder = new OkHttpClient.Builder();
    // 设置超时
    okhttpBuilder.readTimeout(defaultTimeout, defaultTimeoutUnit).connectTimeout(defaultTimeout, defaultTimeoutUnit).writeTimeout(defaultTimeout, defaultTimeoutUnit);
    /**
     * 添加其他自定义拦截器
     */
    for (Interceptor interceptor : interceptorList) {
        okhttpBuilder.addInterceptor(interceptor);
    }
    /**
     *添加公共参数拦截器*
     */
    okhttpBuilder.addInterceptor(commParamsIntInterceptor);
    if (debugMode) {
        /**
         *添加打印日志拦截器*
         */
        okhttpBuilder.addInterceptor(httpInterceptor);
    }
    /**
     *设置证书*
     */
    final X509TrustManager trustManager = new X509TrustManager() {

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

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        if (overlockCard) {
            okhttpBuilder.sslSocketFactory(sslSocketFactory, trustManager).hostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } else {
            if (factory != null) {
                okhttpBuilder.sslSocketFactory(factory, trustManager);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    mOkHttpClient = okhttpBuilder.build();
    retrofitBuilder = new Retrofit.Builder();
    retrofit = retrofitBuilder.baseUrl(baseUrl).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(mOkHttpClient).build();
    this.apiService = retrofit.create(apiService);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(okhttp3.Interceptor) MediaType(okhttp3.MediaType) Request(okhttp3.Request) FormBody(okhttp3.FormBody) SSLSession(javax.net.ssl.SSLSession) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(okhttp3.Response) Retrofit(retrofit2.Retrofit) MultipartBody(okhttp3.MultipartBody) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 30 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project AndroidFastDevFrame by linglongxin24.

the class HttpRequest method getRequestBody.

private String getRequestBody(MultipartBody.Part part) {
    Class<?> personType = part.getClass();
    // 访问私有属性
    Field field = null;
    try {
        field = personType.getDeclaredField("body");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    field.setAccessible(true);
    try {
        RequestBody requestBody = (RequestBody) field.get(part);
        MediaType contentType = requestBody.contentType();
        if (contentType.type().equals("multipart")) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset UTF8 = Charset.forName("UTF-8");
            Charset charset = contentType.charset(UTF8);
            return buffer.readString(charset);
        } else if (contentType.type().equals("image")) {
            return convertFileSize(requestBody.contentLength());
        // Class<?> requestBodyClass = requestBody.getClass();
        // 
        // //访问私有属性
        // Field fileRequestBodyClass = null;
        // try {
        // fileRequestBodyClass = requestBodyClass.getDeclaredField("file");
        // 
        // 
        // fileRequestBodyClass.setAccessible(true);
        // File file = (File) fileRequestBodyClass.get(requestBody);
        // Logger.d("file=" + file.getPath());
        // } catch (NoSuchFieldException e) {
        // e.printStackTrace();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
Also used : Buffer(okio.Buffer) Field(java.lang.reflect.Field) MediaType(okhttp3.MediaType) Charset(java.nio.charset.Charset) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21