List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setMode
public MultipartEntityBuilder setMode(final HttpMultipartMode mode)
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from ww w . ja v a 2 s . co m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @return */ public int attachTestLogsUsingRunId(long testCaseRunId, File filePath) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry6.QMetryRestWebservice.java
/** * attach log using run id//from w ww .j av a 2 s. c o m * * @param token * - token generate using username and password * @param scope * : project:release:cycle * @param testCaseRunId * @param filePath * - absolute path of file to be attached * @param serviceUrl * @param scope * @return */ public int attachTestLogsUsingRunID(String serviceUrl, long testCaseRunId, File filePath, String scope) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments/testLog"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addTextBody("desc", "Attached on " + CurrentDate, org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("type", "TCR", org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addTextBody("entityId", String.valueOf(testCaseRunId), org.apache.http.entity.ContentType.TEXT_PLAIN); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.sat.vcse.automation.utils.http.HttpClient.java
/** * create HttpEntity for multi part file upload * @param file : file to upload, must be in class path * @param contentType//from ww w.ja v a2s.co m * @return HttpEntity * @throws FileNotFoundException */ private HttpEntity getMultiPartEntity(final File file, String formName) throws FileNotFoundException { InputStream is = null; if (file.exists()) { is = new FileInputStream(file); } else { LogHandler.warn("File not found, so trying to read it from class path now"); is = HttpClient.class.getResourceAsStream(file.getPath()); } if (null == formName) { formName = file.getName(); } final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(formName, is, ContentType.MULTIPART_FORM_DATA, file.getName()); return builder.build(); }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/*w ww. j ava 2s .c o m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:org.rundeck.api.ApiCall.java
private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler, HttpEntityEnclosingRequestBase httpPost) { if (null != apiPath.getAccept()) { httpPost.setHeader("Accept", apiPath.getAccept()); }//w w w . j a va 2s .com // POST a multi-part request, with all attachments if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ArrayList<File> tempfiles = new ArrayList<>(); //attach streams for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) { if (client.isUseIntermediateStreamFile()) { //transfer to file File f = copyToTempfile(attachment.getValue()); multipartEntityBuilder.addBinaryBody(attachment.getKey(), f); tempfiles.add(f); } else { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } } if (tempfiles.size() > 0) { handler = TempFileCleanupHandler.chain(handler, tempfiles); } //attach files for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) { multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue()); } httpPost.setEntity(multipartEntityBuilder.build()); } else if (apiPath.getForm().size() > 0) { try { httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e); } } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) { if (client.isUseIntermediateStreamFile()) { ArrayList<File> tempfiles = new ArrayList<>(); File f = copyToTempfile(apiPath.getContentStream()); tempfiles.add(f); httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType()))); handler = TempFileCleanupHandler.chain(handler, tempfiles); } else { InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(entity); } } else if (apiPath.getContents() != null && apiPath.getContentType() != null) { ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(), ContentType.create(apiPath.getContentType())); httpPost.setEntity(bae); } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) { httpPost.setEntity( new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType()))); } else if (apiPath.getXmlDocument() != null) { httpPost.setHeader("Content-Type", "application/xml"); httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument()))); } else if (apiPath.isEmptyContent()) { //empty content } else { throw new IllegalArgumentException("No Form or Multipart entity for POST content-body"); } return execute(httpPost, handler); }
From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java
public int attachTestLogs(long tcVersionIdASEntityId, File filePath) { try {/*from w w w . ja va 2 s . com*/ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss"); final String CurrentDate = format.format(new Date()); Path path = Paths.get(filePath.toURI()); byte[] outFileArray = Files.readAllBytes(path); if (outFileArray != null) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(filePath); builder.addPart("file", bin); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); httppost.addHeader("usertoken", token); httppost.addHeader("scope", scope); CloseableHttpResponse response = httpclient.execute(httppost); String str = null; try { str = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } finally { } JsonElement gson = new Gson().fromJson(str, JsonElement.class); JsonElement data = gson.getAsJsonObject().get("data"); int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString()); return id; } finally { httpclient.close(); } } else { System.out.println(filePath + " file does not exists"); } } catch (Exception ex) { System.out.println("Error in attaching file - " + filePath); System.out.println(ex.getMessage()); } return 0; }
From source file:com.ibm.devops.dra.PublishTest.java
/** * * Send POST request to DLMS back end with the result file * @param bluemixToken - the Bluemix token * @param contents - the result file//from ww w .j a va2 s.c om * @param jobUrl - the build url of the build job in Jenkins * @param timestamp * @return - response/error message from DLMS */ public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException { // create http client and post method CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(this.dlmsUrl); postMethod = addProxyInformation(postMethod); // build up multi-part forms MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (contents != null) { File file = new File(root, contents.getName()); FileBody fileBody = new FileBody(file); builder.addPart("contents", fileBody); builder.addTextBody("test_artifact", file.getName()); if (this.isDeploy) { builder.addTextBody("environment_name", environmentName); } //Todo check the value of lifecycleStage builder.addTextBody("lifecycle_stage", lifecycleStage); builder.addTextBody("url", jobUrl); builder.addTextBody("timestamp", timestamp); String fileExt = FilenameUtils.getExtension(contents.getName()); String contentType; switch (fileExt) { case "json": contentType = CONTENT_TYPE_JSON; break; case "xml": contentType = CONTENT_TYPE_XML; break; default: return "Error: " + contents.getName() + " is an invalid result file type"; } builder.addTextBody("contents_type", contentType); HttpEntity entity = builder.build(); postMethod.setEntity(entity); postMethod.setHeader("Authorization", bluemixToken); } else { return "Error: File is null"; } CloseableHttpResponse response = null; try { response = httpClient.execute(postMethod); // parse the response json body to display detailed info String resStr = EntityUtils.toString(response.getEntity()); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); if (!element.isJsonObject()) { // 401 Forbidden return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString(); } else { JsonObject resJson = element.getAsJsonObject(); if (resJson != null && resJson.has("status")) { return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status"); } else { // other cases return String.valueOf(response.getStatusLine()); } } } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public void postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String boundary = null;/*from w ww .j a v a 2 s .c o m*/ StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; // Log.d("Debug", "JSONParser - command: " + command); if ("start".equals(command) || "startSelected".equals(command)) { url = url + "gui/?action=start&hash=" + hash; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = url + "gui/?action=pause&hash=" + hash; } if ("stop".equals(command) || "stopSelected".equals(command)) { url = url + "gui/?action=stop&hash=" + hash; Log.d("Debug", "Stoping torrent " + hash); } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("addTorrent".equals(command)) { URI hash_uri = null; try { hash_uri = new URI(hash); hash = hash_uri.toString(); // Log.d("Debug","Torrent URL: "+ hash); } catch (URISyntaxException e) { Log.e("Debug", "URISyntaxException: " + e.toString()); } url = url + "gui/?action=add-url&s=" + hash; // key = "urls"; } if ("addTorrentFile".equals(command)) { url = url + "gui/?action=add-file"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; // urlContentType = "multipart/form-data"; } // 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 = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("decreasePrio".equals(command)) { url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("maxPrio".equals(command)) { url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("minPrio".equals(command)) { url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("recheckSelected".equals(command)) { url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash="); } // if ("toggleFirstLastPiecePrio".equals(command)) { // url = "command/toggleFirstLastPiecePrio"; // key = "hashes"; // // } // // if ("toggleSequentialDownload".equals(command)) { // url = "command/toggleSequentialDownload"; // 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, "youTorrent Controller"); 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(); // Set http parameters 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 + "&token=" + token; // Log.d("Debug", "JSONParser - url: " + url); HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } // In order to pass the has we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // Set content type and urls if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".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)) { // Log.d("Debug", "JSONParser - urlContentType: " + urlContentType); // Log.d("Debug", "JSONParser - hash: " + Uri.decode(URLEncoder.encode(hash, "UTF-8"))); // Log.d("Debug", "JSONParser - hash: " + hash); 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("torrent_file", file, ContentType.DEFAULT_BINARY, null); // builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), 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(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); // e.printStackTrace(); 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(); } }
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;/*w w w . ja v a 2 s . 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:com.basistech.rosette.api.RosetteAPI.java
private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter, HttpPost post) {/*from w ww. ja va 2s . com*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMimeSubtype("mixed"); builder.setMode(HttpMultipartMode.STRICT); FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request", // Make sure we're not mislead by someone who puts a charset into the mime type. new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) { @Override public String getFilename() { return null; } @Override public void writeTo(OutputStream out) throws IOException { finalWriter.writeValue(out, request); } @Override public String getTransferEncoding() { return MIME.ENC_BINARY; } @Override public long getContentLength() { return -1; } }); // Either one of 'name=' or 'Content-ID' would be enough. partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\""); partBuilder.setField("Content-ID", "request"); builder.addPart(partBuilder.build()); partBuilder = FormBodyPartBuilder.create("content", new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType()))); partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\""); partBuilder.setField("Content-ID", "content"); builder.addPart(partBuilder.build()); builder.setCharset(StandardCharsets.UTF_8); HttpEntity entity = builder.build(); post.setEntity(entity); }