List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:ua.pp.msk.maven.MavenHttpClient.java
private int execute(File file) throws ArtifactPromotingException { CloseableHttpClient client = HttpClientBuilder.create().build(); int status = -1; try {/* ww w . ja v a 2 s.c om*/ getLog().debug("Connecting to URL: " + url); HttpPost post = new HttpPost(url); post.setHeader("User-Agent", userAgent); if (username != null && username.length() != 0 && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); post.addHeader(new BasicScheme().authenticate(creds, post, null)); } if (file == null) { if (!urlParams.isEmpty()) { post.setEntity(new UrlEncodedFormEntity(urlParams)); } } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (!urlParams.isEmpty()) { for (NameValuePair nvp : urlParams) { builder.addPart(nvp.getName(), new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA)); } } FileBody fb = new FileBody(file); // Not used because of form submission // builder.addBinaryBody("file", file, // ContentType.DEFAULT_BINARY, file.getName()); builder.addPart("file", fb); HttpEntity sendEntity = builder.build(); post.setEntity(sendEntity); } CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); status = statusLine.getStatusCode(); getLog().info( "Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); // Perhaps I need to parse html // String html = EntityUtils.toString(entity); } catch (AuthenticationException ex) { throw new ArtifactPromotingException(ex); } catch (UnsupportedEncodingException ex) { throw new ArtifactPromotingException(ex); } catch (IOException ex) { throw new ArtifactPromotingException(ex); } finally { try { client.close(); } catch (IOException ex) { throw new ArtifactPromotingException("Cannot close http client", ex); } } return status; }
From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java
@Override public void run() { final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager(); final String url = cs.getSnowmanServer().getApiUrl(); for (;;) {/* w w w . ja v a 2 s. c om*/ File obtainedFile; for (;;) { if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) { LOGGER.trace("killFlag == true"); return; } obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile(); if (obtainedFile == null) { Imager.waitALittleBit(300); continue; } else { break; } } boolean doUpload = true; while (doUpload) { try { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httppost = new HttpPost(url); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(uploadNameCameraimage, fb); builder.addTextBody(uploadNameFilename, obtainedFile.getName()); builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername()); builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword()); builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname()); final HttpEntity httpEntity = builder.build(); httppost.setEntity(httpEntity); if (LOGGER.isTraceEnabled()) { LOGGER.trace("executing request " + httppost.getRequestLine()); } try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("response.getStatusLine(): " + response.getStatusLine()); } final HttpEntity resEntity = response.getEntity(); if (resEntity != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength()); } } final String resString = EntityUtils.toString(resEntity).trim(); EntityUtils.consume(resEntity); if (resString.equals(responseSuccess)) { doUpload = false; LOGGER.trace("true: resString.equals(responseSuccess)"); LOGGER.trace("resString: {}", resString); } else { LOGGER.warn("false: resString.equals(responseSuccess)"); LOGGER.warn("resString: {}", resString); // do not flood log files if an error occurred Imager.waitALittleBit(2000); } } } } catch (NoHttpResponseException | SocketException e) { logIOExceptionAndWait(e); } catch (IOException e) { LOGGER.warn("Found unknown IOException", e); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete obtainedFile {}", obtainedFile); } final boolean delete = obtainedFile.delete(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete success {}", delete); } FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile); } }
From source file:hspc.submissionsprogram.AppDisplay.java
AppDisplay() { this.setTitle("Dominion High School Programming Contest"); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.setResizable(false); WindowListener exitListener = new WindowAdapter() { @Override//from w ww . ja v a 2 s . c o m public void windowClosing(WindowEvent e) { System.exit(0); } }; this.addWindowListener(exitListener); JTabbedPane pane = new JTabbedPane(); this.add(pane); JPanel submitPanel = new JPanel(null); submitPanel.setPreferredSize(new Dimension(500, 500)); UIManager.put("FileChooser.readOnly", true); JFileChooser fileChooser = new JFileChooser(); fileChooser.setBounds(0, 0, 500, 350); fileChooser.setVisible(true); FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java"); fileChooser.setFileFilter(javaFilter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setControlButtonsAreShown(false); submitPanel.add(fileChooser); JSeparator separator1 = new JSeparator(); separator1.setBounds(12, 350, 476, 2); separator1.setForeground(new Color(122, 138, 152)); submitPanel.add(separator1); JLabel problemChooserLabel = new JLabel("Problem:"); problemChooserLabel.setBounds(12, 360, 74, 25); submitPanel.add(problemChooserLabel); String[] listOfProblems = Main.Configuration.get("problem_names") .split(Main.Configuration.get("name_delimiter")); JComboBox problems = new JComboBox<>(listOfProblems); problems.setBounds(96, 360, 393, 25); submitPanel.add(problems); JButton submit = new JButton("Submit"); submit.setBounds(170, 458, 160, 30); submit.addActionListener(e -> { try { File file = fileChooser.getSelectedFile(); try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN); builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()), ContentType.TEXT_PLAIN); builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity(); String inputLine; BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent())); try { if ((inputLine = br.readLine()) != null) { int rowIndex = Integer.parseInt(inputLine); new ResultWatcher(rowIndex); } br.close(); } catch (IOException ex) { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } catch (NullPointerException ex) { JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error", JOptionPane.WARNING_MESSAGE); } }); submitPanel.add(submit); JPanel clarificationsPanel = new JPanel(null); clarificationsPanel.setPreferredSize(new Dimension(500, 500)); cList = new JList<>(); cList.setBounds(12, 12, 476, 200); cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); cList.setBackground(new Color(254, 254, 255)); clarificationsPanel.add(cList); JButton viewC = new JButton("View"); viewC.setBounds(12, 224, 232, 25); viewC.addActionListener(e -> { if (cList.getSelectedIndex() != -1) { int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]); clarificationDatas.stream().filter(data -> data.getId() == id).forEach( data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse())); } }); clarificationsPanel.add(viewC); JButton refreshC = new JButton("Refresh"); refreshC.setBounds(256, 224, 232, 25); refreshC.addActionListener(e -> updateCList(true)); clarificationsPanel.add(refreshC); JSeparator separator2 = new JSeparator(); separator2.setBounds(12, 261, 476, 2); separator2.setForeground(new Color(122, 138, 152)); clarificationsPanel.add(separator2); JLabel problemChooserLabelC = new JLabel("Problem:"); problemChooserLabelC.setBounds(12, 273, 74, 25); clarificationsPanel.add(problemChooserLabelC); JComboBox problemsC = new JComboBox<>(listOfProblems); problemsC.setBounds(96, 273, 393, 25); clarificationsPanel.add(problemsC); JTextArea textAreaC = new JTextArea(); textAreaC.setLineWrap(true); textAreaC.setWrapStyleWord(true); textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)), BorderFactory.createEmptyBorder(8, 8, 8, 8))); textAreaC.setBackground(new Color(254, 254, 255)); JScrollPane areaScrollPane = new JScrollPane(textAreaC); areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setBounds(12, 312, 477, 134); clarificationsPanel.add(areaScrollPane); JButton submitC = new JButton("Submit Clarification"); submitC.setBounds(170, 458, 160, 30); submitC.addActionListener(e -> { if (textAreaC.getText().length() > 2048) { JOptionPane.showMessageDialog(this, "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error", JOptionPane.WARNING_MESSAGE); } else if (textAreaC.getText().length() < 20) { JOptionPane.showMessageDialog(this, "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.", "Error", JOptionPane.WARNING_MESSAGE); } else { Connection conn = null; PreparedStatement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"), Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass")); String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID))); stmt.setString(2, String.valueOf(problemsC.getSelectedItem())); stmt.setString(3, String.valueOf(textAreaC.getText())); textAreaC.setText(""); stmt.executeUpdate(); stmt.close(); conn.close(); updateCList(false); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } } } }); clarificationsPanel.add(submitC); pane.addTab("Submit", submitPanel); pane.addTab("Clarifications", clarificationsPanel); Timer timer = new Timer(); TimerTask updateTask = new TimerTask() { @Override public void run() { updateCList(false); } }; timer.schedule(updateTask, 10000, 10000); updateCList(false); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); }
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 ww w.ja v a2 s. 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.DefaultApi.java
/** * Token endpoint//from ww w . j ava 2 s . com * The token endpoint is used to obtain access tokens which allow clients to make API requests * @param authorization Basic authorization token ('Basic <client_key>') * @param grantType Grant type used to obtain the token. * @param acceptLanguage Client locale, as <language>-<country> * @param contentType application/json * @param deviceId Device identifier, must uniquely identify the user or device accessing the API. Required only for \"device_credentials\" grant type * @param refreshToken Refresh token, used to issue a new token without resending client credentials. Required only for \"refresh_token\" grant type * @return AccessToken */ public AccessToken postToken(String authorization, String grantType, String acceptLanguage, String contentType, String deviceId, String refreshToken) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'authorization' is set if (authorization == null) { throw new ApiException(400, "Missing the required parameter 'authorization' when calling postToken"); } // verify the required parameter 'grantType' is set if (grantType == null) { throw new ApiException(400, "Missing the required parameter 'grantType' when calling postToken"); } // create path and map variables String localVarPath = "/token".replaceAll("\\{format\\}", "json"); // query params List<Pair> localVarQueryParams = new ArrayList<Pair>(); // header params Map<String, String> localVarHeaderParams = new HashMap<String, String>(); // form params Map<String, String> localVarFormParams = new HashMap<String, String>(); localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "grant_type", grantType)); localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization)); localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage)); localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType)); String[] localVarContentTypes = { "application/json" }; String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json"; if (localVarContentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); if (deviceId != null) { localVarBuilder.addTextBody("device_id", ApiInvoker.parameterToString(deviceId), ApiInvoker.TEXT_PLAIN_UTF8); } if (refreshToken != null) { localVarBuilder.addTextBody("refresh_token", ApiInvoker.parameterToString(refreshToken), ApiInvoker.TEXT_PLAIN_UTF8); } localVarPostBody = localVarBuilder.build(); } else { // normal form params localVarFormParams.put("device_id", ApiInvoker.parameterToString(deviceId)); localVarFormParams.put("refresh_token", ApiInvoker.parameterToString(refreshToken)); } try { String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType); if (localVarResponse != null) { return (AccessToken) ApiInvoker.deserialize(localVarResponse, "", AccessToken.class); } else { return null; } } catch (ApiException ex) { throw ex; } }
From source file:org.openbaton.sdk.api.util.RestRequest.java
/** * Used to upload tar files to the NFVO for creating VNFPackages. * * @param f the tar file containing the VNFPackage * @return the created VNFPackage object * @throws SDKException/*from ww w .ja va 2 s . c o m*/ */ public VNFPackage requestPostPackage(final File f) throws SDKException { CloseableHttpResponse response = null; HttpPost httpPost = null; try { try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } log.debug("Executing post on " + baseUrl); httpPost = new HttpPost(this.baseUrl); httpPost.setHeader(new BasicHeader("accept", "multipart/form-data")); httpPost.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", f); httpPost.setEntity(multipartEntityBuilder.build()); response = httpClient.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } catch (IOException e) { httpPost.releaseConnection(); throw new SDKException("Could not create VNFPackage from file " + f.getName(), e); } // check response status checkStatus(response, HttpURLConnection.HTTP_OK); // return the response of the request String result = ""; if (response.getEntity() != null) try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.debug("Uploaded the VNFPackage"); log.trace("received: " + result); log.trace("Casting it into: " + VNFPackage.class); httpPost.releaseConnection(); return mapper.fromJson(result, VNFPackage.class); } httpPost.releaseConnection(); return null; }
From source file:org.archive.modules.fetcher.FetchHTTPRequest.java
protected HttpEntity buildPostRequestEntity(CrawlURI curi) { String enctype = (String) curi.getData().get(CoreAttributeConstants.A_SUBMIT_ENCTYPE); if (enctype == null) { enctype = ContentType.APPLICATION_FORM_URLENCODED.getMimeType(); }/*from ww w . jav a2 s. c o m*/ @SuppressWarnings("unchecked") List<NameValue> submitData = (List<NameValue>) curi.getData().get(CoreAttributeConstants.A_SUBMIT_DATA); if (enctype.equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { LinkedList<NameValuePair> nvps = new LinkedList<NameValuePair>(); for (NameValue nv : submitData) { nvps.add(new BasicNameValuePair(nv.name, nv.value)); } try { return new UrlEncodedFormEntity(nvps, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else if (enctype.equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValue nv : submitData) { entityBuilder.addTextBody(escapeForMultipart(nv.name), escapeForMultipart(nv.value)); } return entityBuilder.build(); } else { throw new IllegalStateException("unsupported form submission enctype='" + enctype + "'"); } }
From source file:org.openbaton.marketplace.core.VNFPackageManagement.java
public void dispatch(VNFPackageMetadata vnfPackageMetadata) throws FailedToUploadException { RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(60000) .build();//from w w w.j ava2 s . c o m CloseableHttpResponse response = null; HttpPost httpPost = null; String url = "https://" + fitEagleIp + ":" + fitEaglePort + "/OpenBaton/upload/v2"; try { log.debug("Executing post on " + url); httpPost = new HttpPost(url); // httpPost.setHeader(new BasicHeader("Accept", "multipart/form-data")); // httpPost.setHeader(new BasicHeader("Content-type", "multipart/form-data")); httpPost.setHeader(new BasicHeader("username", userManagement.getCurrentUser())); httpPost.setHeader(new BasicHeader("filename", vnfPackageMetadata.getVnfPackageFileName())); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", vnfPackageMetadata.getVnfPackageFile()); httpPost.setEntity(multipartEntityBuilder.build()); CloseableHttpClient client = getHttpClientForSsl(config); response = client.execute(httpPost); } catch (ClientProtocolException e) { httpPost.releaseConnection(); e.printStackTrace(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } catch (IOException e) { httpPost.releaseConnection(); e.printStackTrace(); httpPost.releaseConnection(); log.error("NotAble to upload VNFPackage"); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } // check response status String result = ""; if (response != null && response.getEntity() != null) { try { result = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); httpPost.releaseConnection(); throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: " + e.getMessage()); } } if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { log.debug("Uploaded the VNFPackage"); log.debug("received: " + result); if (vnfPackageMetadata.getRequirements() == null) { vnfPackageMetadata.setRequirements(new HashMap<String, String>()); } vnfPackageMetadata.getRequirements().put("fiteagle-id", result); } else throw new FailedToUploadException( "Not Able to upload VNFPackage to Fiteagle because: Fiteagle answered " + response.getStatusLine().getStatusCode()); httpPost.releaseConnection(); }
From source file:ConnectionProtccol.HttpClient.java
/** * * @param urlParams// w w w . j a va2 s .c o m * @param postParams * */ public boolean httpPost(String url, MultipartEntityBuilder builder, UrlEncodedFormEntity formParams) { loggerObj.log(Level.INFO, "Inside httpsPost method"); CloseableHttpClient httpclient = HttpClients.createDefault(); try { // HttpPost httppost = new HttpPost("https://reportsapi.zoho.com/api/harshavardhan.r@zohocorp.com/Test/Name_password?ZOHO_ACTION=IMPORT&ZOHO_OUTPUT_FORMAT=json&ZOHO_ERROR_FORMAT=json&authtoken=7ed717b94bc30455aad11ce5d31d34f9&ZOHO_API_VERSION=1.0"); loggerObj.log(Level.INFO, "Going to post to the zoho reports api"); HttpPost httppost = new HttpPost(url); //Need to understand the difference betwween multipartentitybuilder and urlencodedformentity// HttpEntity entity = null; if (builder != null) { entity = builder.build(); } if (formParams != null) { entity = formParams; } httppost.setEntity(entity); loggerObj.log(Level.INFO, "executing request"); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } catch (IOException ex) { loggerObj.log(Level.INFO, "Cannot connect to reports.zoho.com" + ex.toString()); return false; } try { loggerObj.log(Level.INFO, "----------------------------------------"); loggerObj.log(Level.INFO, response.toString()); response.getStatusLine(); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { loggerObj.log(Level.INFO, "Response content length: " + resEntity.getContentLength()); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException ex) { loggerObj.log(Level.INFO, "cannot read the response 1 from reports.zoho.com" + ex.toString()); return false; } catch (UnsupportedOperationException ex) { loggerObj.log(Level.INFO, "cannot read the response 2" + ex.toString()); return false; } String line = ""; try { loggerObj.log(Level.INFO, "reading response line"); while ((line = rd.readLine()) != null) { System.out.println(line); loggerObj.log(Level.INFO, line); } } catch (IOException ex) { loggerObj.log(Level.INFO, "cannot read the response 3" + ex.toString()); return false; } } try { EntityUtils.consume(resEntity); } catch (IOException ex) { loggerObj.log(Level.INFO, "cannot read the response 4" + ex.toString()); return false; } } finally { try { response.close(); } catch (IOException ex) { loggerObj.log(Level.INFO, "cannot close the response" + ex.toString()); return false; } } } finally { try { httpclient.close(); } catch (IOException ex) { loggerObj.log(Level.INFO, "cannot read the https clinet" + ex.toString()); return false; } } return true; }