List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:com.oracle.bdcs.bdm.client.ApiClient.java
License:Apache License
/** * Build HTTP call with the given options. * * @param path 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/*from ww w.j av a 2s .c o m*/ * @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 { String[] auths = { ApiKeyAuth.class.getName() }; updateParamsForAuth(auths, queryParams, headerParams); 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:com.pangbo.android.thirdframworks.retrofit.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 methodError(method, "@Headers value must be in the form \"Name: Value\". Found: \"%s\"", header);/*from w w w . j a va 2 s.c o m*/ } 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.parse.ParseOkHttpClient.java
License:Open Source License
/** * For OKHttpClient, since it does not expose any interface for us to check the raw response * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list, * we use OKHttp inner interceptor list. * @param parseNetworkInterceptor/* w w w . j a v a 2s . c om*/ */ @Override /* package */ void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) { okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(final Chain okHttpChain) throws IOException { Request okHttpRequest = okHttpChain.request(); // Transfer OkHttpRequest to ParseHttpRequest final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest); // Capture OkHttpResponse final Capture<Response> okHttpResponseCapture = new Capture<>(); final ParseHttpResponse parseResponse = parseNetworkInterceptor .intercept(new ParseNetworkInterceptor.Chain() { @Override public ParseHttpRequest getRequest() { return parseRequest; } @Override public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException { // Use OKHttpClient to send request Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest); Response okHttpResponse = okHttpChain.proceed(okHttpRequest); okHttpResponseCapture.set(okHttpResponse); return getResponse(okHttpResponse); } }); final Response okHttpResponse = okHttpResponseCapture.get(); // Ideally we should build newOkHttpResponse only based on parseResponse, however // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so // we rely on the okHttpResponse to generate the builder and change the necessary info // inside Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder(); // Set status newOkHttpResponseBuilder.code(parseResponse.getStatusCode()) .message(parseResponse.getReasonPhrase()); // Set headers if (parseResponse.getAllHeaders() != null) { for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) { newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue()); } } // Set body newOkHttpResponseBuilder.body(new ResponseBody() { @Override public MediaType contentType() { if (parseResponse.getContentType() == null) { return null; } return MediaType.parse(parseResponse.getContentType()); } @Override public long contentLength() throws IOException { return parseResponse.getTotalSize(); } @Override public BufferedSource source() throws IOException { // We need to use the proxy stream from interceptor to replace the origin network // stream, so when the stream is read by Parse, the network stream is proxyed in the // interceptor. if (parseResponse.getContent() == null) { return null; } return Okio.buffer(Okio.source(parseResponse.getContent())); } }); return newOkHttpResponseBuilder.build(); } }); }
From source file:com.parse.ParseOkHttpClientTest.java
License:Open Source License
@Test public void testGetParseResponse() throws IOException { int statusCode = 200; String reasonPhrase = "test reason"; final String content = "test"; final int contentLength = content.length(); final String contentType = "application/json"; String url = "http://www.parse.com/"; Request request = new Request.Builder().url(url).build(); Response okHttpResponse = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1) .code(statusCode).message(reasonPhrase).body(new ResponseBody() { @Override/*w w w . ja v a 2s .c o m*/ public MediaType contentType() { return MediaType.parse(contentType); } @Override public long contentLength() throws IOException { return contentLength; } @Override public BufferedSource source() throws IOException { Buffer buffer = new Buffer(); buffer.write(content.getBytes()); return buffer; } }).build(); ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null); ParseHttpResponse parseResponse = parseClient.getResponse(okHttpResponse); // Verify status code assertEquals(statusCode, parseResponse.getStatusCode()); // Verify reason phrase assertEquals(reasonPhrase, parseResponse.getReasonPhrase()); // Verify content length assertEquals(contentLength, parseResponse.getTotalSize()); // Verify content assertArrayEquals(content.getBytes(), ParseIOUtils.toByteArray(parseResponse.getContent())); }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
License:Open Source License
@SuppressWarnings("deprecation") private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Request.Method.DEPRECATED_GET_OR_POST: // Ensure backwards compatibility. Volley assumes a request with a null body is a GET byte[] postBody = request.getPostBody(); if (postBody != null) { builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody)); }// w ww. jav a 2 s .c o m break; case Request.Method.GET: builder.get(); break; case Request.Method.DELETE: builder.delete(); break; case Request.Method.POST: builder.post(createRequestBody(request)); break; case Request.Method.HEAD: builder.head(); break; case Request.Method.OPTIONS: builder.method("OPTIONS", null); break; case Request.Method.TRACE: builder.method("TRACE", null); break; case Request.Method.PATCH: builder.patch(createRequestBody(request)); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.phattn.vnexpressnews.io.OkHttpStack.java
License:Open Source License
private static RequestBody createRequestBody(Request request) throws AuthFailureError { final byte[] body = request.getBody(); if (body == null) { return null; }//from ww w . j a va 2 s .com return RequestBody.create(MediaType.parse(request.getBodyContentType()), body); }
From source file:com.ringcentral.rc_android_sdk.rcsdk.utils.Helpers.java
License:Open Source License
/** * sendSMS Helper//from w w w . j a va 2s .c o m * @param to * @param from * @param message * @param callback */ public void sendSMS(String to, String from, String message, APICallback callback) { String payload = "{\"to\": [{\"phoneNumber\":\" " + to + "\"}]," + "\"from\": {\"phoneNumber\":\" " + from + "\"}," + "\"text\":\"" + message + "\"}"; RequestBody body = RequestBody.create(MediaType.parse("application/json"), payload.getBytes()); try { platform.post(API.SMS.value, body, null, callback); } catch (AuthException e) { e.printStackTrace(); } }
From source file:com.secupwn.aimsicd.utils.RequestTask.java
@Override protected String doInBackground(String... commandString) { // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc) switch (mType) { // OCID upload request from "APPLICATION" drawer title case DBE_UPLOAD_REQUEST: try {// w ww. j av a 2 s.c o m @Cleanup Realm realm = Realm.getDefaultInstance(); boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm); log.info("OCID upload data prepared - " + String.valueOf(prepared)); if (prepared) { File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv"); publishProgress(25, 100); RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)) .build(); Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv") .post(requestBody).build(); publishProgress(60, 100); Response response = okHttpClient.newCall(request).execute(); publishProgress(80, 100); if (response != null) { log.info("OCID Upload Response: " + response.code() + " - " + response.message()); if (response.code() == 200) { Realm.Transaction transaction = mDbAdapter.ocidProcessed(); realm.executeTransaction(transaction); } publishProgress(95, 100); } return "Successful"; } else { Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing)); return null; } // all caused by httpclient.execute(httppost); } catch (UnsupportedEncodingException e) { log.error("Upload OpenCellID data Exception", e); } catch (FileNotFoundException e) { log.error("Upload OpenCellID data Exception", e); } catch (IOException e) { log.error("Upload OpenCellID data Exception", e); } catch (Exception e) { log.error("Upload OpenCellID data Exception", e); } // DOWNLOADING... case DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title mTimeOut = REQUEST_TIMEOUT_MENU; case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer" int count; try { long total; int progress = 0; String dirName = getOCDBDownloadDirectoryPath(mAppContext); File dir = new File(dirName); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, OCDB_File_Name); log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name); Request request = new Request.Builder().url(commandString[0]).get().build(); Response response; try { // OCID's API can be slow. Give it up to a minute to do its job. Since this // is a backgrounded task, it's ok to wait for a while. okHttpClient.setReadTimeout(60, TimeUnit.SECONDS); response = okHttpClient.newCall(request).execute(); okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default } catch (SocketTimeoutException e) { log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?"); return "Timeout"; } if (response.code() != 200) { try { String error = response.body().string(); Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error); log.error("Download OCID data error: " + error); } catch (Exception e) { Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage()); log.error("Download OCID exception: ", e); } return "Error"; } else { // This returns "-1" for streamed response (Chunked Transfer Encoding) total = response.body().contentLength(); if (total == -1) { log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!"); total = 1024; // Let's set it arbitrarily to something other than "-1" } else { log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total); publishProgress((int) (0.25 * total), (int) total); // Let's show something! } FileOutputStream output = new FileOutputStream(file, false); InputStream input = new BufferedInputStream(response.body().byteStream()); byte[] data = new byte[1024]; while ((count = input.read(data)) > 0) { // writing data to file output.write(data, 0, count); progress += count; publishProgress(progress, (int) total); } input.close(); // flushing output output.flush(); output.close(); } return "Successful"; } catch (IOException e) { log.warn("Problem reading data from steam", e); return null; } } return null; }
From source file:com.shopify.buy.data.MockResponder.java
License:Open Source License
@Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); String key = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement()); JsonElement element = data.get(key); JsonObject responseJson = element.getAsJsonObject(); int code = responseJson.get(KEY_CODE).getAsInt(); String message = responseJson.get(KEY_MESSAGE).getAsString(); String body = responseJson.get(KEY_BODY).getAsString(); if (code >= 400) { retrofit.client.Response retrofitResponse = new retrofit.client.Response(request.urlString(), code, "reason", Collections.EMPTY_LIST, new TypedString(body)); throw RetrofitError.httpError(request.urlString(), retrofitResponse, null, null); }// w w w .j a v a 2s . c o m MediaType contentType = MediaType.parse("application/json; charset=utf-8"); return new Response.Builder().protocol(Protocol.HTTP_1_1).code(code).request(request) .body(ResponseBody.create(contentType, body)).message(message).addHeader("key", "value").build(); }
From source file:com.sonaive.v2ex.util.LoginHelper.java
License:Open Source License
/** After spent hours digging, I give up */ private void signIn(String onceCode) { Map<String, String> params = new HashMap<>(); params.put("next", "/"); params.put("u", mAccountName); params.put("p", mPassword); params.put("once", onceCode); RequestBody postBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), params.toString()); Request request = new Request.Builder().header("Origin", "http://www.v2ex.com") .header("Referer", "http://www.v2ex.com/signin").header("X-Requested-With", "com.android.browser") .header("Cache-Control", "max-age=0") .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") .header("Accept-Language", "zh-CN, en-US") .header("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7") .url(Api.API_URLS.get(Api.API_SIGNIN)).post(postBody).build(); try {/*from w w w . j a va 2s . co m*/ okHttpClient.setFollowRedirects(false); Response response = okHttpClient.newCall(request).execute(); final JsonObject result = new JsonObject(); Pattern errorPattern = Pattern.compile("<div class=\"problem\">(.*)</div>"); Matcher errorMatcher = errorPattern.matcher(response.body().string()); final String errorContent; if (response.code() == 302) {// temporary moved, 302 found, disallow redirects. LOGD(TAG, "sign in success!"); getUserInfo(); return; } else if (errorMatcher.find()) { errorContent = errorMatcher.group(1).replaceAll("<[^>]+>", ""); } else { errorContent = "Unknown error"; } if (errorContent != null) { result.addProperty("result", "fail"); result.addProperty("err_msg", errorContent); LOGD(TAG, "sign in error, err_msg = " + errorContent); } } catch (IOException e) { e.printStackTrace(); } }