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();
}
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;
}
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 "";
}
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);
}
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 "";
}
Aggregations