List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create
public static MultipartEntityBuilder create()
From source file:com.behance.sdk.services.BehanceSDKPublishProjectService.java
private BehanceSDKPublishProjectTaskResult publishProjectOnServer( BehanceSDKPublishProjectServiceParamsDTO paramBehanceSDKPublishProjectServiceParamsDTO, BehanceSDKPublishProjectStatusDTO paramBehanceSDKPublishProjectStatusDTO) { BehanceSDKPublishProjectTaskResult localBehanceSDKPublishProjectTaskResult = new BehanceSDKPublishProjectTaskResult(); BehanceSDKPublishedProjectDTO localBehanceSDKPublishedProjectDTO = new BehanceSDKPublishedProjectDTO(); String str1 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectTitle(); localBehanceSDKPublishedProjectDTO.setProjectTitle(str1); localBehanceSDKPublishProjectTaskResult.setPublishedProject(localBehanceSDKPublishedProjectDTO); List localList = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectModules(); paramBehanceSDKPublishProjectStatusDTO.setProjectTitle(str1); paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_STARTED); paramBehanceSDKPublishProjectStatusDTO .setProgressPercentage(getProgressPercentage(BehanceSDKPublishProjectProgressState.PUBLISH_STARTED, paramBehanceSDKPublishProjectServiceParamsDTO)); broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); Object localObject4 = null; HashMap localHashMap = new HashMap(); localHashMap.put("clientId", paramBehanceSDKPublishProjectServiceParamsDTO.getAppClientId()); Object localObject1 = localObject4; ContentType localContentType;/*from www. ja v a 2s. co m*/ Object localObject5; String str2; try { localContentType = ContentType.create("text/plain", "UTF-8"); localObject1 = localObject4; localObject5 = BehanceSDKUrlUtil.getUrlFromTemplate( "{server_root_url}/v2/project/editor?{key_client_id_param}={clientId}", localHashMap); localObject1 = localObject4; str2 = BehanceSDKUserManager.getInstance().checkExpiryAndGetAccessToken(); Object localObject2 = localObject5; if (str2 != null) { localObject1 = localObject4; localObject2 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject5, "access_token", str2); } localObject1 = localObject4; localObject2 = new HttpPost((String) localObject2); localObject1 = localObject4; localObject6 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCoverImageByteArray(); localObject1 = localObject4; localObject5 = MultipartEntityBuilder.create(); localObject1 = localObject4; localObject6 = new ByteArrayInputStream((byte[]) localObject6); localObject1 = localObject4; ((MultipartEntityBuilder) localObject5).addPart("image", new InputStreamBody((InputStream) localObject6, paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCoverImageFileName())); localObject1 = localObject4; ((MultipartEntityBuilder) localObject5).addTextBody("title", str1, localContentType); localObject1 = localObject4; ((HttpPost) localObject2).setEntity(((MultipartEntityBuilder) localObject5).build()); localObject1 = localObject4; localObject2 = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject2); localObject1 = localObject4; ((ByteArrayInputStream) localObject6).close(); localObject1 = localObject4; if (((HTTPResponse) localObject2).getStatusCode() != 201) { localObject1 = localObject4; paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED); localObject1 = localObject4; paramBehanceSDKPublishProjectStatusDTO .setReasonPhrase(((HTTPResponse) localObject2).getReasonPhrase()); localObject1 = localObject4; broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); localObject1 = localObject4; cleanupCreativeCloudResources(localList); localObject1 = localObject4; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CREATION_FAILED); localObject1 = localObject4; localBehanceSDKPublishProjectTaskResult .setReasonPhrase(((HTTPResponse) localObject2).getReasonPhrase()); return localBehanceSDKPublishProjectTaskResult; } localObject1 = localObject4; localObject2 = (JSONObject) new JSONObject(((HTTPResponse) localObject2).getResponseString()) .get("project"); localObject1 = localObject4; localObject5 = ((JSONObject) localObject2).optString("id"); localObject1 = localObject5; localBehanceSDKPublishedProjectDTO.setProjectId((String) localObject5); localObject1 = localObject5; localObject4 = ((JSONObject) localObject2).optString("url"); localObject1 = localObject5; localBehanceSDKPublishedProjectDTO.setProjectUrl((String) localObject4); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProjectId((String) localObject5); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProjectUrl((String) localObject4); localObject1 = localObject5; if (!isActiveUploadCancelled()) { break label563; } localObject1 = localObject5; handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO, paramBehanceSDKPublishProjectServiceParamsDTO); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED); return localBehanceSDKPublishProjectTaskResult; } catch (Throwable localThrowable) { logger.error(localThrowable, "Problem publishing project", new Object[0]); cleanupCreativeCloudResources(localList); if (!isActiveUploadCancelled()) { break label1715; } } handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO, paramBehanceSDKPublishProjectServiceParamsDTO); localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED); return localBehanceSDKPublishProjectTaskResult; label563: localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PROJECT_DRAFT_CREATION_SUCCESSFUL); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProgressPercentage( getProgressPercentage(BehanceSDKPublishProjectProgressState.PROJECT_DRAFT_CREATION_SUCCESSFUL, paramBehanceSDKPublishProjectServiceParamsDTO)); localObject1 = localObject5; broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); localObject1 = localObject5; localObject4 = localThrowable.optJSONObject("covers"); int i; Iterator localIterator; if (localObject4 != null) { localObject1 = localObject5; localObject3 = ((JSONObject) localObject4).optString("202"); localObject1 = localObject5; localObject4 = ((JSONObject) localObject4).optString("404"); localObject1 = localObject5; localBehanceSDKPublishedProjectDTO.setProjectImageUrl((String) localObject3); if (localObject4 != null) { localObject1 = localObject5; if (((String) localObject4).length() > 0) { localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProjectCoverImageUrl((String) localObject4); } } } else { localObject1 = localObject5; localObject4 = BehanceSDKUrlUtil.getUrlFromTemplate( "{server_root_url}/v2/project/editor/{PROJECTID}/modules?{key_client_id_param}={clientId}", localHashMap).replace("{PROJECTID}", (CharSequence) localObject5); localObject3 = localObject4; if (str2 != null) { localObject1 = localObject5; localObject3 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject4, "access_token", str2); } i = 0; localObject1 = localObject5; localIterator = localList.iterator(); } ProjectModule localProjectModule; label1147: label1173: do { localObject1 = localObject5; if (!localIterator.hasNext()) { break label1284; } localObject1 = localObject5; localProjectModule = (ProjectModule) localIterator.next(); localObject1 = localObject5; if (isActiveUploadCancelled()) { localObject1 = localObject5; handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO, paramBehanceSDKPublishProjectServiceParamsDTO); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED); return localBehanceSDKPublishProjectTaskResult; localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProjectCoverImageUrl((String) localObject3); break; } i += 1; localObject1 = localObject5; ProjectModuleTypes localProjectModuleTypes = localProjectModule.getType(); localObject1 = localObject5; Object localObject7 = MultipartEntityBuilder.create(); localObject6 = null; localObject1 = localObject5; if (localProjectModuleTypes != ProjectModuleTypes.IMAGE) { localObject1 = localObject5; if (localProjectModuleTypes != ProjectModuleTypes.CREATIVECLOUD_ASSET) { } } else { localObject1 = localObject5; ((MultipartEntityBuilder) localObject7).addTextBody("type", "image"); localObject1 = localObject5; localObject4 = ((ImageModule) localProjectModule).getFileForUpload(); localObject1 = localObject5; ((MultipartEntityBuilder) localObject7).addPart("image", new FileBody((File) localObject4)); localObject1 = localObject5; localObject6 = ((MultipartEntityBuilder) localObject7).build(); localObject1 = localObject5; localObject7 = new HttpPost((String) localObject3); localObject1 = localObject5; ((HttpPost) localObject7).setEntity(new CustomHttpEntityWrapper((HttpEntity) localObject6, new ProjectModuleUploadEntityWrapperCallback(paramBehanceSDKPublishProjectServiceParamsDTO, paramBehanceSDKPublishProjectStatusDTO, (HttpPost) localObject7, i, null))); localObject1 = localObject5; localObject6 = BehanceSDKHTTPUtils.doHTTPPost((HttpPost) localObject7); localObject1 = localObject5; if (localProjectModuleTypes != ProjectModuleTypes.IMAGE) { break label1147; } localObject1 = localObject5; if (((File) localObject4).equals(((ImageModule) localProjectModule).getFile())) { break label1147; } localObject1 = localObject5; ((File) localObject4).delete(); } for (;;) { localObject1 = localObject5; if (!isActiveUploadCancelled()) { break label1173; } localObject1 = localObject5; handleCancelAfterSuccessfulUpload(localBehanceSDKPublishedProjectDTO, paramBehanceSDKPublishProjectServiceParamsDTO); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.CANCELLED); return localBehanceSDKPublishProjectTaskResult; localObject1 = localObject5; localObject4 = localObject6; if (localProjectModuleTypes != ProjectModuleTypes.EMBED) { break; } localObject1 = localObject5; ((MultipartEntityBuilder) localObject7).addTextBody("type", "embed"); localObject1 = localObject5; ((MultipartEntityBuilder) localObject7).addPart("html", new StringBody( ((EmbedModule) localProjectModule).getEmbedContent(), ContentType.APPLICATION_XHTML_XML)); localObject4 = localObject6; break; localObject1 = localObject5; if (localProjectModuleTypes == ProjectModuleTypes.CREATIVECLOUD_ASSET) { localObject1 = localObject5; localProjectModule.deleteFromFileSystem(); } } localObject1 = localObject5; } while (((HTTPResponse) localObject6).getStatusCode() == 201); localObject1 = localObject5; deleteProject((String) localObject5, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap); localObject1 = localObject5; cleanupCreativeCloudResources(localList); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setReasonPhrase(((HTTPResponse) localObject6).getReasonPhrase()); localObject1 = localObject5; broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.MODULE_ADD_FAILED); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult.setFailedMoudle(localProjectModule); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult.setReasonPhrase(((HTTPResponse) localObject6).getReasonPhrase()); return localBehanceSDKPublishProjectTaskResult; label1284: localObject1 = localObject5; localObject4 = BehanceSDKUrlUtil.getUrlFromTemplate( "{server_root_url}/v2/project/editor/{PROJECTID}?{key_client_id_param}={clientId}", localHashMap) .replace("{PROJECTID}", (CharSequence) localObject5); Object localObject3 = localObject4; if (str2 != null) { localObject1 = localObject5; localObject3 = BehanceSDKUrlUtil.appendQueryStringParam((String) localObject4, "access_token", str2); } localObject1 = localObject5; localObject4 = new HttpPut((String) localObject3); localObject1 = localObject5; Object localObject6 = MultipartEntityBuilder.create(); localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).setMode(HttpMultipartMode.BROWSER_COMPATIBLE); localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("title", str1, localContentType); localObject1 = localObject5; localObject3 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCreativeFields(); localObject1 = localObject5; if (!TextUtils.isEmpty((CharSequence) localObject3)) { localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("fields", (String) localObject3, localContentType); } localObject1 = localObject5; localObject3 = paramBehanceSDKPublishProjectServiceParamsDTO.getProjectTags(); localObject1 = localObject5; if (!TextUtils.isEmpty((CharSequence) localObject3)) { localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("tags", (String) localObject3, localContentType); } localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("description", paramBehanceSDKPublishProjectServiceParamsDTO.getProjectDescription(), localContentType); localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("license", paramBehanceSDKPublishProjectServiceParamsDTO.getProjectCopyright(), localContentType); localObject1 = localObject5; if (paramBehanceSDKPublishProjectServiceParamsDTO.isProjectContainsAdultContent()) { } for (localObject3 = "1";; localObject3 = "0") { localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("mature_content", (String) localObject3, localContentType); localObject1 = localObject5; ((MultipartEntityBuilder) localObject6).addTextBody("published", "1", localContentType); localObject1 = localObject5; ((HttpPut) localObject4).setEntity(((MultipartEntityBuilder) localObject6).build()); localObject1 = localObject5; localObject3 = BehanceSDKHTTPUtils.doHTTPPut((HttpPut) localObject4); localObject1 = localObject5; if (((HTTPResponse) localObject3).getStatusCode() == 200) { localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.SUCCESS); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.MODULES_UPLOAD_SUCCESSFUL); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setProgressPercentage( getProgressPercentage(BehanceSDKPublishProjectProgressState.MODULES_UPLOAD_SUCCESSFUL, paramBehanceSDKPublishProjectServiceParamsDTO)); localObject1 = localObject5; broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); return localBehanceSDKPublishProjectTaskResult; } localObject1 = localObject5; deleteProject((String) localObject5, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED); localObject1 = localObject5; paramBehanceSDKPublishProjectStatusDTO.setReasonPhrase(((HTTPResponse) localObject3).getReasonPhrase()); localObject1 = localObject5; broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.PUBLISH_FAILED); localObject1 = localObject5; localBehanceSDKPublishProjectTaskResult .setReasonPhrase(((HTTPResponse) localObject3).getReasonPhrase()); return localBehanceSDKPublishProjectTaskResult; label1715: if (!TextUtils.isEmpty(localObject1)) { deleteProject(localObject1, paramBehanceSDKPublishProjectServiceParamsDTO, localHashMap); } paramBehanceSDKPublishProjectStatusDTO .setProgressState(BehanceSDKPublishProjectProgressState.PUBLISH_FAILED); paramBehanceSDKPublishProjectStatusDTO.setException((Throwable) localObject3); broadcastProgressUpdate(paramBehanceSDKPublishProjectStatusDTO); localBehanceSDKPublishProjectTaskResult .setStatus(BehanceSDKPublishProjectTaskResult.PublishStatus.EXCEPTION); localBehanceSDKPublishProjectTaskResult.setException((Throwable) localObject3); return localBehanceSDKPublishProjectTaskResult; } }
From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java
private void addFiles() throws cfmRunTimeException { List<fileDescriptor> files = httpData.getFiles(); if (files.size() > 0) { if (message instanceof HttpPost && (isMultipart || httpData.getFiles().size() > 0)) { if (multipartEntityBuilder == null) multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset); for (int i = 0; i < files.size(); i++) { fileDescriptor nextFile = files.get(i); multipartEntityBuilder.addPart(nextFile.getName(), new FileBody(nextFile.getFile(), ContentType.create(nextFile.getMimeType()), nextFile.getFile().getName())); }/* w w w. j a v a2 s . c om*/ } else if (message instanceof HttpPut) { fileDescriptor nextFile = files.get(0); // just use the first file specified try { FileInputStream fileIn = new FileInputStream(nextFile.getFile()); InputStreamEntity entity = new InputStreamEntity(fileIn, nextFile.getFile().length(), ContentType.create(nextFile.getMimeType())); ((HttpPut) message).setEntity(entity); } catch (FileNotFoundException e) { throw newRunTimeException("Failed to locate file " + nextFile.getFile().getAbsolutePath()); } } } }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String limit = ""; String tracker = ""; String boundary = null;/*from ww w . j a va 2s .c o m*/ String fileId = ""; String filePriority = ""; String result = ""; StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; String label = ""; if ("start".equals(command) || "startSelected".equals(command)) { url = "command/resume"; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = "command/pause"; } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = "command/delete"; key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = "command/deletePerm"; key = "hashes"; } if ("addTorrent".equals(command)) { url = "command/download"; key = "urls"; } if ("addTracker".equals(command)) { url = "command/addTrackers"; key = "hash"; } if ("addTorrentFile".equals(command)) { url = "command/upload"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; } if ("pauseall".equals(command)) { url = "command/pauseall"; } if ("pauseAll".equals(command)) { url = "command/pauseAll"; } if ("resumeall".equals(command)) { url = "command/resumeall"; } if ("resumeAll".equals(command)) { url = "command/resumeAll"; } if ("increasePrio".equals(command)) { url = "command/increasePrio"; key = "hashes"; } if ("decreasePrio".equals(command)) { url = "command/decreasePrio"; key = "hashes"; } if ("maxPrio".equals(command)) { url = "command/topPrio"; key = "hashes"; } if ("minPrio".equals(command)) { url = "command/bottomPrio"; key = "hashes"; } if ("setFilePrio".equals(command)) { url = "command/setFilePrio"; String[] tmpString = hash.split("&"); hash = tmpString[0]; fileId = tmpString[1]; filePriority = tmpString[2]; // Log.d("Debug", "hash: " + hash); // Log.d("Debug", "fileId: " + fileId); // Log.d("Debug", "filePriority: " + filePriority); } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("setUploadRateLimit".equals(command)) { url = "command/setTorrentsUpLimit"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } } if ("setDownloadRateLimit".equals(command)) { url = "command/setTorrentsDlLimit"; key = "hashes"; Log.d("Debug", "Hash before: " + hash); String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } // Log.d("Debug", "url: " + url); // Log.d("Debug", "Hashes: " + hash + " | limit: " + limit); } if ("recheckSelected".equals(command)) { url = "command/recheck"; } if ("toggleFirstLastPiecePrio".equals(command)) { url = "command/toggleFirstLastPiecePrio"; key = "hashes"; } if ("toggleSequentialDownload".equals(command)) { url = "command/toggleSequentialDownload"; key = "hashes"; } if ("toggleAlternativeSpeedLimits".equals(command)) { // Log.d("Debug", "Toggling alternative rates"); url = "command/toggleAlternativeSpeedLimits"; key = "hashes"; } if ("setLabel".equals(command)) { url = "command/setLabel"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("setCategory".equals(command)) { url = "command/setCategory"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("alternativeSpeedLimitsEnabled".equals(command)) { // Log.d("Debug", "Getting alternativeSpeedLimitsEnabled"); url = "command/alternativeSpeedLimitsEnabled"; key = "hashes"; } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } if ("addTracker".equals(command)) { String[] tmpString = hash.split("&"); hash = tmpString[0]; URI hash_uri = new URI(hash); hash = hash_uri.toString(); try { tracker = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { tracker = ""; } // Log.d("Debug", "addTracker - hash: " + hash); // Log.d("Debug", "addTracker - tracker: " + tracker); } // In order to pass the hash we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); // Add limit if (!limit.equals("")) { Log.d("Debug", "JSONParser - Limit: " + limit); nvps.add(new BasicNameValuePair("limit", limit)); } // Set values for setting file priority if ("setFilePrio".equals(command)) { nvps.add(new BasicNameValuePair("id", fileId)); nvps.add(new BasicNameValuePair("priority", filePriority)); } // Add label if (label != null && !label.equals("")) { label = Uri.decode(label); if ("setLabel".equals(command)) { nvps.add(new BasicNameValuePair("label", label)); } else { nvps.add(new BasicNameValuePair("category", label)); } // Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<"); } // Add tracker if (tracker != null && !tracker.equals("")) { nvps.add(new BasicNameValuePair("urls", tracker)); // Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<"); } String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8); // This replaces encoded char "+" for "%20" so spaces can be passed as parameter entityValue = entityValue.replaceAll("\\+", "%20"); StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8); stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); httpget.setEntity(stringEntity); // Set content type and urls if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command) || "setFilePrio".equals(command) || "toggleAlternativeSpeedLimits".equals(command) || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command) || "setCategory".equals(command) || "addTracker".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); // Log.d("Debug", "JSONPArser - command result: " + result); return result; } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (SSLPeerUnverifiedException e) { Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString()); throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return null; }
From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java
public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException { HttpClient httpclient = null;// w ww.j a va 2 s.co m org.apache.http.HttpResponse response = null; try { httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httppost = new HttpPost(this.endpoint); httppost.setConfig(requestConfig); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(PARAM_NAME_CHANGE_ICON, new FileBody(appIcon)); builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN)); builder.addPart(PARAM_NAME_APPLICATION_HASH_ID, new StringBody(applicationHash, ContentType.TEXT_PLAIN)); httppost.setEntity(builder.build()); httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE)); response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity()); throw new AppCloudIntegrationTestException("Update app icon failed " + result); } } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) { // In most of the cases, even though connection is timed out, actual activity is completed. // And this will be asserted so if it failed due to a valid case, it will be captured. log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1); } catch (IOException e) { log.error("Failed to invoke app icon update API.", e); throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpclient); } }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties, ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset) throws Exception { String method = httpDispatcherProperties.getMethod(); boolean isMultipart = httpDispatcherProperties.isMultipart(); Map<String, List<String>> headers = httpDispatcherProperties.getHeaders(); Map<String, List<String>> parameters = httpDispatcherProperties.getParameters(); Object content = null;//from w ww. j av a2s .c o m if (httpDispatcherProperties.isDataTypeBinary()) { content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(), connectorMessage, null, true); } else { content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(), connectorMessage); // If text mode is used and a specific charset isn't already defined, use the one from the connector properties if (contentType.getCharset() == null) { contentType = HttpMessageConverter.setCharset(contentType, charset); } } // populate the query parameters List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size()); for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) { for (String value : parameterEntry.getValue()) { logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]"); queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value)); } } HttpRequestBase httpMethod = null; HttpEntity httpEntity = null; URIBuilder uriBuilder = new URIBuilder(hostURI); // create the method if ("GET".equalsIgnoreCase(method)) { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpGet(uriBuilder.build()); } else if ("POST".equalsIgnoreCase(method)) { if (isMultipart) { logger.debug("setting multipart file content"); setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPost(uriBuilder.build()); if (content instanceof String) { FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false); } else { FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false); } MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart(tempFile.getName(), new FileBody(tempFile, contentType, tempFile.getName())); httpEntity = multipartEntityBuilder.build(); } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(), ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { httpMethod = new HttpPost(uriBuilder.build()); httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset()); } else { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPost(uriBuilder.build()); if (content instanceof String) { httpEntity = new StringEntity((String) content, contentType); } else { httpEntity = new ByteArrayEntity((byte[]) content); } } } else if ("PUT".equalsIgnoreCase(method)) { if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(), ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { httpMethod = new HttpPut(uriBuilder.build()); httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset()); } else { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpPut(uriBuilder.build()); if (content instanceof String) { httpEntity = new StringEntity((String) content, contentType); } else { httpEntity = new ByteArrayEntity((byte[]) content); } } } else if ("DELETE".equalsIgnoreCase(method)) { setQueryString(uriBuilder, queryParameters); httpMethod = new HttpDelete(uriBuilder.build()); } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { // Compress the request entity if necessary List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers) .get(HTTP.CONTENT_ENCODING); if (CollectionUtils.isNotEmpty(contentEncodingList)) { for (String contentEncoding : contentEncodingList) { if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip") || contentEncoding.toLowerCase().equals("x-gzip"))) { httpEntity = new GzipCompressingEntity(httpEntity); break; } } } ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity); } // set the headers for (Entry<String, List<String>> headerEntry : headers.entrySet()) { for (String value : headerEntry.getValue()) { logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]"); httpMethod.addHeader(headerEntry.getKey(), value); } } // Only set the Content-Type for entity-enclosing methods, but not if multipart is used if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) { httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString()); } return httpMethod; }
From source file:io.swagger.client.api.CameraApi.java
/** * Start liveview/*from www. j av a 2s. co m*/ * * @return void */ public void liveviewStartPost() throws TimeoutException, ExecutionException, InterruptedException, ApiException { Object postBody = null; // create path and map variables String path = "/liveview/start".replaceAll("\\{format\\}", "json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); String[] contentTypes = { }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] {}; try { String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if (localVarResponse != null) { return; } else { return; } } catch (ApiException ex) { throw ex; } catch (InterruptedException ex) { throw ex; } catch (ExecutionException ex) { if (ex.getCause() instanceof VolleyError) { VolleyError volleyError = (VolleyError) ex.getCause(); if (volleyError.networkResponse != null) { throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } } throw ex; } catch (TimeoutException ex) { throw ex; } }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
/** * upload a file and update an existing resource with it * * @param resourceUUID// w w w . jav a2 s .c o m * @param filename * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndUpdateResource(String resourceUUID, String filename, String name, String description) throws Exception { if (null == resourceUUID) throw new Exception("ID of the resource to update was null."); String responseJson = null; String file = config.getProperty("resource.watchfolder") + File.separatorChar + filename; // ggf. Preprocessing: insert CDATA in XML and write new XML file to tmp folder if (Boolean.parseBoolean(config.getProperty("resource.preprocessing"))) { Document document = new SAXBuilder().build(new File(file)); file = config.getProperty("preprocessing.folder") + File.separatorChar + UUID.randomUUID() + ".xml"; XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file)); out.output(new SAXBuilder().build(new StringReader( XmlTransformer.xmlOutputter(document, config.getProperty("preprocessing.xslt"), null))), bufferedWriter); } finally { if (bufferedWriter != null) { bufferedWriter.close(); } } } // upload CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPut httpPut = new HttpPut(config.getProperty("engine.dswarm.api") + "resources/" + resourceUUID); FileBody fileBody = new FileBody(new File(file)); StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileBody) .addPart("name", stringBodyForName).addPart("description", stringBodyForDescription).build(); httpPut.setEntity(reqEntity); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPut.getRequestLine()); CloseableHttpResponse httpResponse = httpclient.execute(httpPut); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return responseJson; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
/** * Send data using HTTP POST method to the server named by vhost * * @param url address to request on the server * @param vhost name of the server at address which should respond. When null, localhost is assumed. * @param post data to send (name-value-pairs) * @param userName user name for HTTP authentication : only sent when requesting localhost * @param password encoded password for HTTP authentication : only sent when requesting localhost * @param usegzip if the body should be gzipped * @return response body/*from w ww . ja va2 s. com*/ * @throws IOException when an error occurred */ public byte[] POSTbytes(final MultiProtocolURL url, final String vhost, final Map<String, ContentBody> post, final String userName, final String password, final boolean usegzip, final boolean concurrent) throws IOException { final HttpPost httpPost = new HttpPost(url.toNormalform(true)); final boolean localhost = Domains.isLocalhost(url.getHost()); if (!localhost) setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service if (vhost == null) setHost(Domains.LOCALHOST); final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); for (final Entry<String, ContentBody> part : post.entrySet()) entityBuilder.addPart(part.getKey(), part.getValue()); final HttpEntity multipartEntity = entityBuilder.build(); // statistics this.upbytes = multipartEntity.getContentLength(); if (usegzip) { httpPost.setEntity(new GzipCompressingEntity(multipartEntity)); } else { httpPost.setEntity(multipartEntity); } if (!localhost || password == null) { return getContentBytes(httpPost, Integer.MAX_VALUE, concurrent); } byte[] content = null; final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", url.getPort()), new UsernamePasswordCredentials(userName, password)); /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */ final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry).build(); try { this.httpResponse = httpclient.execute(httpPost); try { HttpEntity httpEntity = this.httpResponse.getEntity(); if (httpEntity != null) { if (getStatusCode() == HttpStatus.SC_OK) { content = getByteArray(httpEntity, Integer.MAX_VALUE); } // Ensures that the entity content is fully consumed and the content stream, if exists, is closed. EntityUtils.consume(httpEntity); } } finally { this.httpResponse.close(); } } finally { httpclient.close(); } return content; }
From source file:io.swagger.client.api.CameraApi.java
/** * Start liveview// ww w .jav a 2 s.c om * */ public void liveviewStartPost(final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) { Object postBody = null; // create path and map variables String path = "/liveview/start".replaceAll("\\{format\\}", "json"); // query params List<Pair> queryParams = new ArrayList<Pair>(); // header params Map<String, String> headerParams = new HashMap<String, String>(); // form params Map<String, String> formParams = new HashMap<String, String>(); String[] contentTypes = { }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; } else { // normal form params } String[] authNames = new String[] {}; try { apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames, new Response.Listener<String>() { @Override public void onResponse(String localVarResponse) { responseListener.onResponse(localVarResponse); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { errorListener.onErrorResponse(error); } }); } catch (ApiException ex) { errorListener.onErrorResponse(new VolleyError(ex)); } }