List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:de.ebf.UploadFileOneSkyAppMojo.java
License:Apache License
private void uploadFiles() throws MojoExecutionException { try {/*www . ja va 2 s .c o m*/ for (File file : files) { System.out.println(String.format("Uploading %1$s", file.getName())); OkHttpClient okHttpClient = new OkHttpClient(); final String url = String.format( API_ENDPOINT + "projects/%1$s/files?file_format=%2$s&locale=%3$s&%4$s", projectId, fileFormat, locale, getAuthParams()); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addPart( Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"" + file.getName() + "\""), RequestBody.create(MediaType.parse("text/plain"), file)) .build(); final Request request = new Request.Builder().post(requestBody).url(url).build(); final Response response = okHttpClient.newCall(request).execute(); if (response.code() == 201) { System.out.println(String.format("Successfully uploaded %1$s", file.getName())); } else { throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s, %3$s", response.code(), response.message(), response.body().string())); } } } catch (IOException | MojoExecutionException ex) { if (failOnError == null || failOnError) { throw new MojoExecutionException(ex.getMessage(), ex); } else { System.out.println("Caught exception: " + ex.getMessage()); } } }
From source file:de.feike.tiingoclient.ApiClient.java
License:Apache License
/** * Build HTTP call with the given options. * * @param path//from ww w. j a v a 2s. c o m * The sub-path of the HTTP URL * @param method * The request method, one of "GET", "HEAD", "OPTIONS", "POST", * "PUT", "PATCH" and "DELETE" * @param queryParams * The query parameters * @param body * The request body object * @param headerParams * The header parameters * @param formParams * The form parameters * @param authNames * The authentications to apply * @param progressRequestListener * Progress request listener * @return The HTTP call * @throws ApiException * If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if (progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return httpClient.newCall(request); }
From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java
License:Apache License
/** * Posts the content of a buffer of bytes to a server via a HTTP POST request. * @param url - URL target of this request * @param mediaType - Content-Type header for this request * @param supplier - supplies the content of this request * @param callback - is called back when the response is readable */// w ww .j a va2 s.co m public void asyncPostBytes(final String url, final String mediaType, final Supplier<byte[]> supplier, final Callback callback) { final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected"); final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected"); requireNonNull(supplier, "A valid supplier expected"); requireNonNull(callback, "A valid callback expected"); // prepare request final Request request = new Request.Builder().url(url2).post(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(mediaType2 + "; charset=utf-8"); } @Override public void writeTo(final BufferedSink sink) throws IOException { sink.write(supplier.get()); } }).build(); // submit request client.newCall(request).enqueue(callback); }
From source file:es.upv.grycap.coreutils.fiber.http.Http2Client.java
License:Apache License
/** * Puts the content of a buffer of bytes to a server via a HTTP PUT request. * @param url - URL target of this request * @param mediaType - Content-Type header for this request * @param supplier - supplies the content of this request * @param callback - is called back when the response is readable */// w ww. ja v a 2 s .com public void asyncPutBytes(final String url, final String mediaType, final Supplier<byte[]> supplier, final Callback callback) { final String url2 = requireNonNull(trimToNull(url), "A non-empty URL expected"); final String mediaType2 = requireNonNull(trimToNull(mediaType), "A non-empty media type expected"); requireNonNull(supplier, "A valid supplier expected"); requireNonNull(callback, "A valid callback expected"); // prepare request final Request request = new Request.Builder().url(url2).put(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(mediaType2 + "; charset=utf-8"); } @Override public void writeTo(final BufferedSink sink) throws IOException { sink.write(supplier.get()); } }).build(); // submit request client.newCall(request).enqueue(callback); }
From source file:feign.okhttp.OkHttpClient.java
License:Apache License
static Request toOkHttpRequest(feign.Request input) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(input.url());//from w w w. j av a 2 s .c o m MediaType mediaType = null; boolean hasAcceptHeader = false; for (String field : input.headers().keySet()) { if (field.equalsIgnoreCase("Accept")) { hasAcceptHeader = true; } for (String value : input.headers().get(field)) { if (field.equalsIgnoreCase("Content-Type")) { mediaType = MediaType.parse(value); if (input.charset() != null) { mediaType.charset(input.charset()); } } else { requestBuilder.addHeader(field, value); } } } // Some servers choke on the default accept string. if (!hasAcceptHeader) { requestBuilder.addHeader("Accept", "*/*"); } RequestBody body = input.body() != null ? RequestBody.create(mediaType, input.body()) : null; requestBuilder.method(input.method(), body); return requestBuilder.build(); }
From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java
License:Apache License
public Request getRequestForAuthentication(String mEmail, String mPassword) { final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8"); final OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder().add("grant_type", "password").add("username", mEmail) .add("password", mPassword).build(); return new Request.Builder().url(currentPath + "/api/token") .header("content-type", "application/x-www-form-urlencoded").post(formBody).build(); }
From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java
License:Apache License
public Request getRequestForAuthenticationClientCredentialsFlow(String mEmail, String mPassword) { final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8"); final OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder().add("grant_type", "client_credentials") .add("client_id", mEmail).add("client_secret", mPassword).build(); return new Request.Builder().url(currentPath + "/api/token") .header("content-type", "application/x-www-form-urlencoded").post(formBody).build(); }
From source file:in.futuretrucks.UploadDriverDocumentsActivity.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { finalFile = null;/* w w w .j a v a 2 s . com*/ if (requestCode == REQUEST_CAMERA) { Bitmap photo = (Bitmap) data.getExtras().get("data"); // CALL THIS METHOD TO GET THE URI FROM THE BITMAP Uri tempUri = getImageUri(appContext, photo); // CALL THIS METHOD TO GET THE ACTUAL PATH finalFile = new File(getRealPathFromURI(tempUri)); profile_pic_path = finalFile.getAbsolutePath(); String uri = "file://" + profile_pic_path; if (pic_request == Constant.DRIVER_PROFILE_PHOTO) { DriverImageDocUploadService service = ServiceGenerator .createService(DriverImageDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); Toast.makeText(appContext, R.string.not_driver_image, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { } }); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwProfilePicDoc)), options); } else if (pic_request == Constant.DRIVER_ADDRESS_PROOF) { DriverAddressProofDocUploadService service = ServiceGenerator .createService(DriverAddressProofDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_address_proof, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwDriverAddressProof)), options); } else if (pic_request == Constant.DRIVER_LICENSE) { DriverLicenseDocUploadService service = ServiceGenerator .createService(DriverLicenseDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_license, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); Log.e("ComeON", "after upload"); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwDriverLicense)), options); } else if (pic_request == Constant.DRIVER_POLICE_VERIFICATION) { PoliceVerificationDocUploadService service = ServiceGenerator .createService(PoliceVerificationDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_police_verification, Toast.LENGTH_LONG) .show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); Log.e("ComeON", "after upload"); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwPoliceVerification)), options); } } else if (requestCode == SELECT_FILE) { Uri selectedImageUri = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String FilePath = cursor.getString(columnIndex); cursor.close(); finalFile = new File(FilePath); profile_pic_path = finalFile.getAbsolutePath(); String uri = "file://" + profile_pic_path; if (pic_request == Constant.DRIVER_PROFILE_PHOTO) { DriverImageDocUploadService service = ServiceGenerator .createService(DriverImageDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { Toast.makeText(appContext, R.string.not_driver_image, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { } }); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwProfilePicDoc)), options); } else if (pic_request == Constant.DRIVER_ADDRESS_PROOF) { DriverAddressProofDocUploadService service = ServiceGenerator .createService(DriverAddressProofDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_address_proof, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwDriverAddressProof)), options); } else if (pic_request == Constant.DRIVER_LICENSE) { DriverLicenseDocUploadService service = ServiceGenerator .createService(DriverLicenseDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_license, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); Log.e("ComeON", "after upload"); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwDriverLicense)), options); } else if (pic_request == Constant.DRIVER_POLICE_VERIFICATION) { PoliceVerificationDocUploadService service = ServiceGenerator .createService(PoliceVerificationDocUploadService.class); File file = new File(profile_pic_path); String mimeType = getMimeType(profile_pic_path); RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file); String jwt = PreferenceClass.getStringPreferences(appContext, Constant.USER_TOKEN); String user_id = PreferenceClass.getStringPreferences(appContext, Constant.NEW_DRIVER_REG_ID); Call<UploadDriverFileApiResponse> call = service.upload(user_id, jwt, requestBody); call.enqueue(new Callback<UploadDriverFileApiResponse>() { @Override public void onResponse(Response<UploadDriverFileApiResponse> response, Retrofit retrofit) { System.out.println("response.code(): " + response.code()); System.out.println("response.code(): " + response.code()); Log.e("ComeON", Integer.toString(response.code())); Toast.makeText(appContext, R.string.not_driver_police_verification, Toast.LENGTH_LONG) .show(); } @Override public void onFailure(Throwable t) { Log.e("ComeON", t.getMessage()); } }); Log.e("ComeON", "after upload"); imageLoader.displayImage(uri, ((ImageView) findViewById(R.id.imgvwPoliceVerification)), options); } } } }
From source file:io.apptik.comm.jus.okhttp.JusOk.java
License:Apache License
public static RequestBody okBody(NetworkRequest request) { if (request == null || (request.contentType == null && request.data == null)) return null; MediaType mediaType = null;// w w w .j a v a 2 s . c o m if (request.contentType != null) { mediaType = MediaType.parse(request.contentType.toString()); } return RequestBody.create(mediaType, request.data); }
From source file:io.bitfactory.mobileclimatemonitor.SlackReporter.java
License:Apache License
@Background protected void sendValuesToSlack() { if (temperatureValue == 0) { return;//from www . ja v a 2 s.co m } if (humidityValue == 0) { return; } try { JSONObject jsonObject = new JSONObject(); jsonObject.put("text", Helper.formatTemperature(temperatureValue) + "\n" + Helper.formatHumidity(humidityValue)); jsonObject.put("channel", slackChannel); jsonObject.put("username", slackSenderName); jsonObject.put("icon_emoji", ":cubimal_chick:"); MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8"); Request request = new Request.Builder().url(new URL(slackWebhookUrl)) .post(RequestBody.create(MEDIA_TYPE_JSON, jsonObject.toString())).build(); new OkHttpClient().newCall(request).execute(); } catch (IOException | JSONException e) { e.printStackTrace(); } temperatureValue = 0; humidityValue = 0; }