Search in sources :

Example 51 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project okhttputils by hongyangAndroid.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response) {
    try {
        // ===>response log
        Log.e(tag, "========response'log=======");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        Log.e(tag, "url : " + clone.request().url());
        Log.e(tag, "code : " + clone.code());
        Log.e(tag, "protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message()))
            Log.e(tag, "message : " + clone.message());
        if (showResponse) {
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    Log.e(tag, "responseBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        String resp = body.string();
                        Log.e(tag, "responseBody's content : " + resp);
                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
        }
        Log.e(tag, "========response'log=======end");
    } catch (Exception e) {
    // e.printStackTrace();
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 52 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project MasterProject by Alexsogge.

the class UploadWorker method uploadMultipartFile.

private int uploadMultipartFile(File file, String uploadToken) throws IOException {
    // uploadProgressBar.setProgress(0);
    MediaType media_type = MEDIA_TYPE_ZIP;
    if (file.getName().substring(file.getName().length() - 4).equals(".mkv"))
        media_type = MEDIA_TYPE_MKV;
    if (file.getName().substring(file.getName().length() - 4).equals(".csv"))
        media_type = MEDIA_TYPE_CSV;
    if (file.getName().substring(file.getName().length() - 4).equals(".3gp"))
        media_type = MEDIA_TYPE_3GP;
    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addPart(Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"" + file.getName() + "\""), RequestBody.create(media_type, file)).build();
    /*
        // we use a ProgressRequestBody to get events for current upload status and visualize this with a progressbar
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, new ProgressRequestBody.Listener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength) {
                float percentage = 100f * bytesWritten / contentLength;
                if(percentage > previousProgress + 5){
                    previousProgress = (int)percentage;
                    sendUploadProgress((int)percentage);
                }

//                    uploadProgressBar.setProgress((int)percentage);
                //publishProgress(String.valueOf(Math.round(percentage)));
            }
        });
        */
    String serverUrl = configs.getString(context.getString(R.string.conf_serverName), "") + serverUrlSuffix + uploadToken;
    Request request = new Request.Builder().url(serverUrl).addHeader("Authorization", "Bearer " + configs.getString(context.getString(R.string.conf_serverToken), "")).post(requestBody).build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            Log.e("upload", "error during upload of " + file.getName());
            throw new IOException(context.getString(R.string.str_unexpected_code) + response);
        } else {
            File directory = file.getParentFile();
            // test if this is last file and delete directory if this is the case
            boolean deleteDirectory = true;
            for (String remainedFile : directory.list()) {
                if (!(remainedFile.charAt(0) == '.' || remainedFile.equals(file.getName())))
                    deleteDirectory = false;
            }
            if (deleteDirectory) {
                for (File remainedFile : directory.listFiles()) {
                    remainedFile.delete();
                }
                directory.delete();
            } else
                // remove file after upload
                file.delete();
            return STATUS_SUCCESS;
        }
    }
}
Also used : Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) MediaType(okhttp3.MediaType) IOException(java.io.IOException) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 53 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project nlp4j by oyahiroki.

the class Main2 method main.

public static void main(String[] args) throws Exception {
    String url = "https://api.ce-cotoha.com/api/dev" + "/nlp/v1/parse";
    String sentence = "日産自動車の車を買いました。";
    String type = "default";
    String access_token = "";
    Gson gson = new Gson();
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("sentence", sentence);
    jsonObj.addProperty("type", type);
    OkHttpClient client = new OkHttpClient();
    MediaType JSON = MediaType.get("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, jsonObj.toString());
    Request request = // 
    new Request.Builder().addHeader("Content-Type", // 
    "application/json;charset=UTF-8").addHeader("Authorization", // 
    "Bearer " + access_token).url(// 
    url).post(// 
    body).build();
    try (Response response = client.newCall(request).execute()) {
        int responseCode = response.code();
        String originalResponseBody = response.body().string();
        System.err.println(responseCode);
        System.err.println(response.headers().toString());
        System.err.println(originalResponseBody);
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 54 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project android-chat by wildfirechat.

the class ClientService method uploadFile.

// progress, error, success
private void uploadFile(String filePath, String uploadUrl, String remoteUrl, UploadMediaCallback callback) {
    if (okHttpClient == null) {
        okHttpClient = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS).build();
    }
    MediaType type = MediaType.parse("application/octet-stream");
    File file = new File(filePath);
    RequestBody fileBody = new UploadFileRequestBody(RequestBody.create(type, file), callback::onProgress);
    Request request = new Request.Builder().url(uploadUrl).put(fileBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            callback.onFail(4);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.code() != 200) {
                Log.e(TAG, "uploadMediaFail " + response.code());
                callback.onFail(4);
            } else {
                callback.onSuccess(remoteUrl);
            }
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) FriendRequest(cn.wildfirechat.model.FriendRequest) ProtoFriendRequest(cn.wildfirechat.model.ProtoFriendRequest) IOException(java.io.IOException) Response(okhttp3.Response) UploadMediaCallback(cn.wildfirechat.remote.UploadMediaCallback) Callback(okhttp3.Callback) MediaType(okhttp3.MediaType) MessageContentMediaType(cn.wildfirechat.message.MessageContentMediaType) File(java.io.File) MemoryFile(android.os.MemoryFile) RequestBody(okhttp3.RequestBody)

Example 55 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project rundeck-cli by rundeck.

the class Keys method prepareKeyUpload.

static RequestBody prepareKeyUpload(final Upload options) throws IOException, InputError {
    MediaType contentType = getUploadContentType(options.getType());
    if (null == contentType) {
        throw new InputError(String.format("Type is not supported: %s", options.getType()));
    }
    RequestBody requestBody;
    if (options.getType() != KeyStorageItem.KeyFileType.password && !options.isFile()) {
        throw new InputError(String.format("File (-f/--file) is required for type: %s", options.getType()));
    }
    if (options.getType() == KeyStorageItem.KeyFileType.password && !options.isFile() && !options.isPrompt()) {
        throw new InputError(String.format("File (-f/--file) or -P/--prompt is required for type: %s", options.getType()));
    }
    if (options.isFile()) {
        File input = options.getFile();
        if (!input.canRead() || !input.isFile()) {
            throw new InputError(String.format("File is not readable or does not exist: %s", input));
        }
        if (options.getType() == KeyStorageItem.KeyFileType.password) {
            // read the first line of the file only, and leave off line breaks
            CharBuffer buffer = CharBuffer.allocate((int) input.length());
            buffer.mark();
            try (InputStreamReader read = new InputStreamReader(new FileInputStream(input), options.isCharset() ? Charset.forName(options.getCharset()) : Charset.defaultCharset())) {
                int len = read.read(buffer);
                while (len > 0) {
                    len = read.read(buffer);
                }
            }
            buffer.reset();
            // locate first newline char
            int limit = 0;
            for (; limit < buffer.length(); limit++) {
                char c = buffer.charAt(limit);
                if (c == '\r' || c == '\n') {
                    break;
                }
            }
            buffer.limit(limit);
            if (buffer.length() == 0) {
                throw new IllegalStateException("No content found in file: " + input);
            }
            ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(buffer);
            requestBody = RequestBody.create(contentType, Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()));
        } else {
            requestBody = RequestBody.create(contentType, input);
        }
    } else {
        char[] chars = System.console().readPassword("Enter password: ");
        ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars));
        requestBody = RequestBody.create(contentType, Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()));
    }
    return requestBody;
}
Also used : InputError(org.rundeck.client.tool.InputError) CharBuffer(java.nio.CharBuffer) MediaType(okhttp3.MediaType) ByteBuffer(java.nio.ByteBuffer) 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