List of usage examples for com.squareup.okhttp MediaType parse
public static MediaType parse(String string)
From source file:com.google.caliper.runner.resultprocessor.OkHttpUploadHandler.java
License:Apache License
@Override public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) { HttpUrl url = HttpUrl.get(uri);// w w w. j ava 2s . co m if (apiKey.isPresent()) { url = url.newBuilder().addQueryParameter("key", apiKey.get().toString()).build(); } RequestBody body = RequestBody.create(MediaType.parse(mediaType), content); Request request = new Request.Builder().url(url).post(body).build(); try { Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return true; } else { ResultsUploader.logger.fine("Failed upload response: " + response.code()); } } catch (IOException e) { ResultsUploader.logUploadFailure(trial, e); } return false; }
From source file:com.google.minijoe.sys.Eval.java
License:Apache License
public void evalNative(int index, JsArray stack, int sp, int parCount) { switch (index) { case ID_HTTP_GET: try {/* w w w . j a v a 2 s. c om*/ String url = stack.getString(sp + 2); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_POST_JSON: try { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), stack.getString(sp + 3)); Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CRAWLER: try { Crawler.startCrawler(stack.getString(sp + 2)); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CURL: new Thread(new Curl()).start(); break; case ID_EXTRACT_HTML: try { Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3)); readability.init(); stack.setObject(sp, readability.outerHtml()); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } break; case ID_EVAL: try { stack.setObject(sp, eval(stack.getString(sp + 2), stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3))); } catch (Exception e) { throw new RuntimeException("" + e); } break; case ID_COMPILE: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); Eval.compile(code, System.out); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOAD: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); //xxx.js Eval.eval(code, Eval.createGlobal()); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_GEN_SITEMAP: try { // create web sitemap for web http://www.javavids.com WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com"); // add some URLs webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0) .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date())); webSitemapGenerator.addPage(new WebPage().setName("latest.php")); webSitemapGenerator.addPage(new WebPage().setName("contact.php")); // generate sitemap and save it to file /var/www/sitemap.xml File file = new File("/var/www/sitemap.xml"); webSitemapGenerator.constructAndSaveSitemap(file); // inform Google that this sitemap has changed webSitemapGenerator.pingGoogle(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_WHOIS: try { stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2))); } catch (WhoisException e) { stack.setObject(sp, "Whois Exception " + e.getMessage()); } catch (HostNameValidationException e) { stack.setObject(sp, "Whois host name invalid " + e.getMessage()); } break; case ID_PAGERANK: stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2))); break; case ID_SEND_TWITTER: try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out .print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(stack.getString(sp + 2)); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } break; case ID_EXTRACT_TEXT: try { String url = stack.getString(sp + 2); String selector = stack.getString(sp + 3); Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get(); HtmlToPlainText formatter = new HtmlToPlainText(); if (selector != null) { Elements elements = doc.select(selector); StringBuffer sb = new StringBuffer(); for (Element element : elements) { String plainText = formatter.getPlainText(element); sb.append(plainText); } stack.setObject(sp, sb.toString()); } else { stack.setObject(sp, formatter.getPlainText(doc)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LIST_LINKS: try { String url = stack.getString(sp + 2); print("Fetching %s...", url); Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); Elements media = doc.select("[src]"); Elements imports = doc.select("link[href]"); print("\nMedia: (%d)", media.size()); for (Element src : media) { if (src.tagName().equals("img")) print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), trim(src.attr("alt"), 20)); else print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); } print("\nImports: (%d)", imports.size()); for (Element link : imports) { print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel")); } print("\nLinks: (%d)", links.size()); for (Element link : links) { print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOG: log.info(stack.getString(sp + 2)); break; case ID_SEND_MAIL: try { // put your e-mail address here final String yourAddress = "guilherme.@gmail.com"; // configure programatically your mail server info EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password"); // and go! new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress) .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send(); } catch (Exception ex) { stack.setObject(sp, "[ERROR]" + ex.getMessage()); } break; case ID_SNAPPY: try { String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of " + "Snappy, a fast compresser/decompresser."; byte[] compressed = Snappy.compress(input.getBytes("UTF-8")); byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length); String result = new String(uncompressed, "UTF-8"); System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_OPENBROWSER: new Thread(new Runnable() { public void run() { openBrowser(); } }).start(); break; case ID_HELP: Enumeration ex = this.keys(); while (ex.hasMoreElements()) { String key = (String) ex.nextElement(); Object val = this.getRawInPrototypeChain(key); if (val instanceof JsFunction) { System.out.println(key + "---" + ((JsFunction) val).description); } else { System.out.println(key + "---" + val); } } break; default: super.evalNative(index, stack, sp, parCount); } }
From source file:com.granita.contacticloudsync.syncadapter.CalendarSyncManager.java
License:Open Source License
@Override protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException { log.info("Downloading " + toDownload.size() + " events (" + MAX_MULTIGET + " at once)"); // download new/updated iCalendars from server for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) {// www . j av a 2 s . c o m if (Thread.interrupted()) return; log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote.get("text/calendar"); String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag; Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVEvent(remote.fileName(), eTag, stream, charset); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()])); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME); if (calendarData == null || calendarData.iCalendar == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes()); processVEvent(remote.fileName(), eTag, stream, charset); } } } }
From source file:com.granita.contacticloudsync.syncadapter.ContactsSyncManager.java
License:Open Source License
@Override protected void downloadRemote() throws IOException, HttpException, DavException, ContactsStorageException { log.info("Downloading " + toDownload.size() + " contacts (" + MAX_MULTIGET + " at once)"); // prepare downloader which may be used to download external resource like contact photos Contact.Downloader downloader = new ResourceDownloader(httpClient, collectionURL); // download new/updated VCards from server for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) {/*w w w . jav a 2s. c o m*/ if (Thread.interrupted()) return; log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote .get("text/vcard;version=4.0, text/vcard;charset=utf-8;q=0.8, text/vcard;q=0.5"); String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag; Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVCard(remote.fileName(), eTag, stream, charset, downloader); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davAddressBook().multiget(urls.toArray(new HttpUrl[urls.size()]), hasVCard4); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } AddressData addressData = (AddressData) remote.properties.get(AddressData.NAME); if (addressData == null || addressData.vCard == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(addressData.vCard.getBytes()); processVCard(remote.fileName(), eTag, stream, charset, downloader); } } } }
From source file:com.granita.contacticloudsync.syncadapter.TasksSyncManager.java
License:Open Source License
@Override protected void downloadRemote() throws IOException, HttpException, DavException, CalendarStorageException { log.info("Downloading " + toDownload.size() + " tasks (" + MAX_MULTIGET + " at once)"); // download new/updated iCalendars from server for (DavResource[] bunch : ArrayUtils.partition(toDownload.toArray(new DavResource[toDownload.size()]), MAX_MULTIGET)) {/* w w w . j av a 2 s .c om*/ if (Thread.interrupted()) return; log.info("Downloading " + StringUtils.join(bunch, ", ")); if (bunch.length == 1) { // only one contact, use GET DavResource remote = bunch[0]; ResponseBody body = remote.get("text/calendar"); String eTag = ((GetETag) remote.properties.get(GetETag.NAME)).eTag; Charset charset = Charsets.UTF_8; MediaType contentType = body.contentType(); if (contentType != null) charset = contentType.charset(Charsets.UTF_8); @Cleanup InputStream stream = body.byteStream(); processVTodo(remote.fileName(), eTag, stream, charset); } else { // multiple contacts, use multi-get List<HttpUrl> urls = new LinkedList<>(); for (DavResource remote : bunch) urls.add(remote.location); davCalendar().multiget(urls.toArray(new HttpUrl[urls.size()])); // process multiget results for (DavResource remote : davCollection.members) { String eTag; GetETag getETag = (GetETag) remote.properties.get(GetETag.NAME); if (getETag != null) eTag = getETag.eTag; else throw new DavException("Received multi-get response without ETag"); Charset charset = Charsets.UTF_8; GetContentType getContentType = (GetContentType) remote.properties.get(GetContentType.NAME); if (getContentType != null && getContentType.type != null) { MediaType type = MediaType.parse(getContentType.type); if (type != null) charset = type.charset(Charsets.UTF_8); } CalendarData calendarData = (CalendarData) remote.properties.get(CalendarData.NAME); if (calendarData == null || calendarData.iCalendar == null) throw new DavException("Received multi-get response without address data"); @Cleanup InputStream stream = new ByteArrayInputStream(calendarData.iCalendar.getBytes()); processVTodo(remote.fileName(), eTag, stream, charset); } } } }
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {/*from ww w . jav a 2s .com*/ String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized CFile uploadFile(@NonNull File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }//from w ww . java 2s . c om // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", file.getName()); params.put("parent", new JSONObject().put("id", parent != null ? parent.getId() : getRoot().getId())); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(file)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("attributes", params.toString()) .addFormDataPart("file", file.getName(), RequestBody.create(fileType, file)).build(); Request request = new Request.Builder().url(API_UPLOAD_URL + "/files/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray entries = jsonObject.getJSONArray("entries"); return buildFile(entries.getJSONObject(0)); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized CFile updateFile(@NonNull CFile file, File content) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }// w w w. j ava2 s . c om // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(content)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("file", content.getName(), RequestBody.create(fileType, content)).build(); Request request = new Request.Builder().url(API_UPLOAD_URL + "/files/" + file.getId() + "/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { // new file created JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray entries = jsonObject.getJSONArray("entries"); return buildFile(entries.getJSONObject(0)); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java
License:Apache License
@Override public CFile uploadFile(@NonNull File file, @Nullable CFolder parent) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }//from www.j av a 2 s .c om Uri uri = Uri.parse(mContentUrl); String url = uri.buildUpon().appendEncodedPath("nodes").build().toString(); // create parameter as json final JSONObject params = new JSONObject(); try { params.put("name", file.getName()); params.put("kind", "FILE"); ArrayList<String> parentList = new ArrayList<>(); parentList.add(parent != null ? parent.getId() : getRoot().getId()); params.put("parents", new JSONArray(parentList)); } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(file)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("metadata", params.toString()) .addFormDataPart("content", file.getName(), RequestBody.create(fileType, file)).build(); Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).post(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { JSONObject jsonObject = new JSONObject(response.body().string()); return buildFile(jsonObject); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }
From source file:com.he5ed.lib.cloudprovider.apis.CloudDriveApi.java
License:Apache License
@Override public CFile updateFile(@NonNull CFile file, File content) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* w w w . ja v a2s. c o m*/ Uri uri = Uri.parse(mContentUrl); String url = uri.buildUpon().appendEncodedPath("nodes/" + file.getId() + "/content").build().toString(); // create multipart body MediaType fileType = MediaType.parse(FilesUtils.getFileType(content)); RequestBody multipart = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("content", file.getName(), RequestBody.create(fileType, content)).build(); Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).put(multipart).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { JSONObject jsonObject = new JSONObject(response.body().string()); return buildFile(jsonObject); } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }