List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:com.heroiclabs.sdk.android.HttpClient.java
License:Apache License
/** {@inheritDoc} */ public <T> Deferred<Response<T>> execute(final @NonNull Request<T> request) { final Deferred<Response<T>> deferred = new Deferred<>(); // Select the host, implicitly only allow HTTPS. HttpUrl.Builder urlBuilder = new HttpUrl.Builder().scheme("https") .host(getServer(request.getDestination())); // Encode and add the path elements. for (final String p : getPath(request.getRequestType(), request.getIdentifiers())) { urlBuilder = urlBuilder.addPathSegment(p); }/*from w w w . ja v a2 s.c o m*/ // Encode and add the query parameters, toString() values as we go. for (final Map.Entry<String, ?> e : request.getParameters().entrySet()) { urlBuilder = urlBuilder.addQueryParameter(e.getKey(), e.getValue().toString()); } final HttpUrl url = urlBuilder.build(); final String token = request.getSession() == null ? "" : request.getSession().getToken(); final String authorization = "Basic " + ByteString.of((apiKey + ":" + token).getBytes()).base64(); final String contentType = "application/json"; final String body = getBody(request.getRequestType(), request.getEntity()); // Construct the HTTP request. final com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().url(url) .method(getMethod(request.getRequestType()), body == null ? null : RequestBody.create(MediaType.parse(contentType), body)) .header("User-Agent", USER_AGENT).header("Content-Type", contentType).header("Accept", contentType) .header("Authorization", authorization).build(); // Prepare a HTTP client instance to execute against. final OkHttpClient client = this.client.clone(); // Interceptors fire in the order they're declared. // Note: Compress first, so we don't re-compress for retried requests. if (this.compressRequests) { client.interceptors().add(GzipRequestInterceptor.INSTANCE); } final int maxAttempts = request.getMaxAttempts() < 1 ? this.maxAttempts : request.getMaxAttempts(); client.interceptors().add(new RetryInterceptor(maxAttempts)); // Log the outgoing request. if (log.isDebugEnabled()) { log.debug("Request: Method{" + httpRequest.method() + "} URL{" + httpRequest.urlString() + "} Headers{" + httpRequest.headers().toString() + "} Body{" + body + "}"); } // Send the request and retrieve a response. client.newCall(httpRequest).enqueue(new Callback() { @Override public void onFailure(final com.squareup.okhttp.Request httpRequest, final IOException e) { // Log the request failure reason. if (log.isDebugEnabled()) { log.debug("Request Failed", e); } deferred.callback(new ErrorResponse(e.getMessage(), e, request)); } @Override public void onResponse(final @NonNull com.squareup.okhttp.Response httpResponse) throws IOException { switch (httpResponse.code()) { // Good response with body. case HttpURLConnection.HTTP_OK: final String responseBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + responseBody + "}"); } final T entity = codec.deserialize(responseBody, request.getResponseType()); deferred.callback(new SuccessResponse<>(request, httpResponse.code(), responseBody, entity)); break; // Good response, no body. case HttpURLConnection.HTTP_NO_CONTENT: case HttpURLConnection.HTTP_CREATED: // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Success: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "}"); } deferred.callback(new SuccessResponse<>(request, httpResponse.code(), null, null)); break; // Error response. default: final String errorBody = httpResponse.body().string(); // Log the incoming response. if (log.isDebugEnabled()) { log.debug("Response Error: Method{" + httpResponse.request().method() + "} URL{" + httpResponse.request().urlString() + "} Code{" + httpResponse.code() + "} Message{" + httpResponse.message() + "} Headers:{" + httpResponse.headers().toString() + "} Body{" + errorBody + "}"); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") final ErrorDetails error = errorBody.isEmpty() ? new ErrorDetails(httpResponse.code(), httpResponse.message() == null ? "unknown" : httpResponse.message(), null) : codec.deserialize(errorBody, ErrorDetails.class); deferred.callback(new ErrorResponse(error.getMessage(), error, request)); } // Indicate that application-layer response processing is complete. httpResponse.body().close(); } }); return deferred; }
From source file:com.hileone.restretrofit.request.RequestBuilder.java
License:Apache License
void addHeader(String name, String value) { if ("Content-Type".equalsIgnoreCase(name)) { contentType = MediaType.parse(value); } else {//from ww w .ja v a 2 s . c o m requestBuilder.addHeader(name, value); } }
From source file:com.hileone.restretrofit.request.RequestFactoryParser.java
License:Apache License
private com.squareup.okhttp.Headers parseHeaders(String[] headers) { com.squareup.okhttp.Headers.Builder builder = new com.squareup.okhttp.Headers.Builder(); for (String header : headers) { int colon = header.indexOf(':'); if (colon == -1 || colon == 0 || colon == header.length() - 1) { throw RestUtils.methodError(method, "@Headers value must be in the form \"Name: Value\". Found: \"%s\"", header); }/*from w ww. j a va 2 s. c om*/ String headerName = header.substring(0, colon); String headerValue = header.substring(colon + 1).trim(); if ("Content-Type".equalsIgnoreCase(headerName)) { contentType = MediaType.parse(headerValue); } else { builder.add(headerName, headerValue); } } return builder.build(); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareReply(OkHttpClient okHttpClient, ACReplyStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"resto\""), RequestBody.create(null, StringUtils.avoidNull(struct.resto))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }/* w w w . ja v a 2s . c om*/ InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_REPLY; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Call prepareCreatePost(OkHttpClient okHttpClient, ACPostStruct struct) throws Exception { MultipartBuilder builder = new MultipartBuilder(); builder.type(MultipartBuilder.FORM); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"name\""), RequestBody.create(null, StringUtils.avoidNull(struct.name))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"email\""), RequestBody.create(null, StringUtils.avoidNull(struct.email))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""), RequestBody.create(null, StringUtils.avoidNull(struct.title))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"content\""), RequestBody.create(null, StringUtils.avoidNull(struct.content))); builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"fid\""), RequestBody.create(null, StringUtils.avoidNull(struct.fid))); if (struct.water) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"water\""), RequestBody.create(null, "true")); }// w w w .j a va 2 s . com InputStreamPipe isPipe = struct.image; if (isPipe != null) { String filename; MediaType mediaType; byte[] bytes; File file = compressBitmap(isPipe, struct.imageType); if (file == null) { String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(struct.imageType); if (TextUtils.isEmpty(extension)) { extension = "jpg"; } filename = "a." + extension; mediaType = MediaType.parse(struct.imageType); if (mediaType == null) { mediaType = MEDIA_TYPE_IMAGE_ALL; } try { isPipe.obtain(); bytes = IOUtils.getAllByte(isPipe.open()); } finally { isPipe.close(); isPipe.release(); } } else { filename = "a.jpg"; mediaType = MEDIA_TYPE_IMAGE_JPEG; InputStream is = null; try { is = new FileInputStream(file); bytes = IOUtils.getAllByte(is); } finally { IOUtils.closeQuietly(is); file.delete(); } } builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"image\"; filename=\"" + filename + "\""), RequestBody.create(mediaType, bytes)); } String url = ACUrl.API_CREATE_POST; Log.d(TAG, url); Request request = new GoodRequestBuilder(url).post(builder.build()).build(); return okHttpClient.newCall(request); }
From source file:com.howareyoudoing.data.net.RestApiImpl.java
License:Apache License
private String getUserEntitiesFromApi() throws MalformedURLException { String s = "{ \"token\": \"fdca03ce3cf55a3bc5612f91f69176e5632826118694a53ecf4e1622cfa5c7013b52a195faafe0bfe91bec406ed99735\", \"request\": { \"interface\": \"ServiceInterface\", \"method\": \"getAllUsers\", \"parameters\": { } } }"; MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, s); return ApiConnection.createPOST(API_BASE_URL, body).requestSyncCall(); }
From source file:com.ibm.bluemix.appid.android.internal.userattributesmanager.UserAttributeManagerImpl.java
License:Apache License
private void sendProtectedRequest(String method, String name, String value, AccessToken accessToken, final UserAttributeResponseListener listener) { String url = Config.getUserProfilesServerUrl(AppID.getInstance()) + USER_PROFILE_ATTRIBUTES_PATH; url = (name == null || name.length() == 0) ? url : url + '/' + name; AppIDRequest req = new AppIDRequest(url, method); ResponseListener resListener = new ResponseListener() { @Override//from w ww. j av a2 s . c om public void onSuccess(Response response) { String responseText = response.getResponseText() == null || response.getResponseText().equals("") ? "{}" : response.getResponseText(); try { listener.onSuccess(new JSONObject(responseText)); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Response response, Throwable t, JSONObject extendedInfo) { String message = (t != null) ? t.getLocalizedMessage() : ""; message = (extendedInfo != null) ? message + " : " + extendedInfo.toString() : message; logger.error(message); int errorCode = (response != null) ? response.getStatus() : 500; UserAttributesException.Error error; switch (errorCode) { case 401: error = UserAttributesException.Error.UNAUTHORIZED; break; case 404: error = UserAttributesException.Error.NOT_FOUND; break; default: error = UserAttributesException.Error.FAILED_TO_CONNECT; break; } listener.onFailure(new UserAttributesException(error)); } }; RequestBody requestBody = (value == null || value.length() == 0) ? null : RequestBody.create(MediaType.parse("application/json"), value); req.send(resListener, requestBody, accessToken); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java
License:Apache License
/** * Send this resource request asynchronously, with the given string as the request body. * If no content type header was set, this method will set it to "text/plain". * * @param requestBody The request body text * @param listener The listener whose onSuccess or onFailure methods will be called when this request finishes. *///from w w w .j av a 2s .c o m protected void send(final String requestBody, final ResponseListener listener) { String contentType = headers.get(CONTENT_TYPE); if (contentType == null) { contentType = TEXT_PLAIN; } RequestBody body = RequestBody.create(MediaType.parse(contentType), requestBody); sendRequest(listener, body); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java
License:Apache License
/** * Send this resource request asynchronously, with the given JSON object as the request body. * If no content type header was set, this method will set it to "application/json". * * @param json The JSON object to put in the request body * @param listener The listener whose onSuccess or onFailure methods will be called when this request finishes. *//* www.ja v a 2 s.com*/ protected void send(JSONObject json, ResponseListener listener) { String contentType = headers.get(CONTENT_TYPE); if (contentType == null) { contentType = JSON_CONTENT_TYPE; } RequestBody body = RequestBody.create(MediaType.parse(contentType), json.toString()); sendRequest(listener, body); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java
License:Apache License
/** * Send this resource request asynchronously, with the content of the given byte array as the request body. * Note that this method does not set any content type header, if such a header is required it must be set before calling this method. * * @param data The byte array containing the request body * @param listener The listener whose onSuccess or onFailure methods will be called when this request finishes. *///w ww .j a v a2 s . co m protected void send(byte[] data, ResponseListener listener) { RequestBody body = RequestBody.create(MediaType.parse(headers.get(CONTENT_TYPE)), data); sendRequest(listener, body); }