List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequestToLarge() throws IOException { TestHttpClient client = new TestHttpClient(); try {//from ww w .j a v a2 s .c om String uri = DefaultServer.getDefaultServerURL() + "/servletContext/2"; HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile()))); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(DefaultServer.isH2() || DefaultServer.isAjp() ? StatusCodes.SERVICE_UNAVAILABLE : StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } catch (IOException expected) { //in some environments the forced close of the read side will cause a connection reset } finally { client.getConnectionManager().shutdown(); } }
From source file:com.cloudapp.rest.CloudApi.java
/** * Upload a file to the CloudApp servers. * /*from w ww. j a va 2s . c o m*/ * @param input * The inputstream that holds the content that should be stored on the server. * @param filename * The name of this file. i.e.: README.txt * @return A JSONObject with the returned output from the CloudApp servers. * @throws CloudApiException */ @SuppressWarnings("rawtypes") public JSONObject uploadFile(CloudAppInputStream stream) throws CloudApiException { HttpGet keyRequest = null; HttpPost uploadRequest = null; try { // Get a key for the file first. keyRequest = new HttpGet("http://my.cl.ly/items/new"); keyRequest.addHeader("Accept", "application/json"); // Execute the request. HttpResponse response = client.execute(keyRequest); int status = response.getStatusLine().getStatusCode(); if (status == 200) { String body = EntityUtils.toString(response.getEntity()); JSONObject json = new JSONObject(body); String url = json.getString("url"); JSONObject params = json.getJSONObject("params"); // From the API docs // Use this response to construct the upload. Each item in params becomes a // separate parameter you'll need to post to url. Send the file as the parameter // file. MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // Add all the plain parameters. Iterator keys = params.keys(); while (keys.hasNext()) { String key = (String) keys.next(); entity.addPart(key, new StringBody(params.getString(key))); } // Add the actual file. // We have to use the 'file' parameter for the S3 storage. entity.addPart("file", stream); uploadRequest = new HttpPost(url); uploadRequest.addHeader("Accept", "application/json"); uploadRequest.setEntity(entity); // Perform the actual upload. // uploadMethod.setFollowRedirects(true); response = client.execute(uploadRequest); status = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); if (status == 200) { return new JSONObject(body); } throw new CloudApiException(status, "Was unable to upload the file to amazon:\n" + body, null); } throw new CloudApiException(500, "Was unable to retrieve a key from CloudApp to upload a file.", null); } catch (IOException e) { LOGGER.error("Error when trying to upload a file.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (JSONException e) { LOGGER.error("Error when trying to convert the return output to JSON.", e); throw new CloudApiException(500, e.getMessage(), e); } finally { if (keyRequest != null) { keyRequest.abort(); } if (uploadRequest != null) { uploadRequest.abort(); } } }
From source file:org.doctester.testbrowser.TestBrowserImpl.java
private Response makePostOrPutRequest(Request httpRequest) { org.apache.http.HttpResponse apacheHttpClientResponse; Response response = null;/*from w w w . j ava 2 s . c o m*/ try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpEntityEnclosingRequestBase apacheHttpRequest; if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPost(httpRequest.uri); } else { apacheHttpRequest = new HttpPut(httpRequest.uri); } if (httpRequest.headers != null) { // add all headers for (Entry<String, String> header : httpRequest.headers.entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } /////////////////////////////////////////////////////////////////// // Either add form parameters... /////////////////////////////////////////////////////////////////// if (httpRequest.formParameters != null) { List<BasicNameValuePair> formparams = Lists.newArrayList(); for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add multipart file upload /////////////////////////////////////////////////////////////////// if (httpRequest.filesToUpload != null) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) { // For File parameters entity.addPart(entry.getKey(), new FileBody((File) entry.getValue())); } apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add payload and convert if Json or Xml /////////////////////////////////////////////////////////////////// if (httpRequest.payload != null) { if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) { String string = new ObjectMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType("application/json; charset=utf-8"); apacheHttpRequest.setEntity(entity); } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) { String string = new XmlMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8); apacheHttpRequest.setEntity(new StringEntity(string, "utf-8")); } else if (httpRequest.payload instanceof String) { StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8"); apacheHttpRequest.setEntity(entity); } else { StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8"); apacheHttpRequest.setEntity(entity); } } setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects); // Here we go! apacheHttpClientResponse = httpClient.execute(apacheHttpRequest); response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse); apacheHttpRequest.releaseConnection(); } catch (IOException e) { logger.error("Fatal problem creating POST or PUT request in TestBrowser", e); throw new RuntimeException(e); } return response; }
From source file:org.semantictools.web.upload.AppspotUploadClient.java
public void upload(String contentType, String path, File file) throws IOException { if (file.getName().equals(CHECKSUM_PROPERTIES)) { return;/*from ww w. java2 s . com*/ } if (!path.startsWith("/")) { path = "/" + path; } // Do not upload if we can confirm that we previously uploaded // the same content. String checksumKey = path.concat(".sha1"); String checksumValue = null; try { checksumValue = Checksum.sha1(file); String prior = checksumProperties.getProperty(checksumKey); if (checksumValue.equals(prior)) { return; } } catch (NoSuchAlgorithmException e) { // Ignore. } logger.debug("uploading... " + path); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(servletURL); post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx", Charset.forName("UTF-8")); FileBody body = new FileBody(file, contentType); entity.addPart(CONTENT_TYPE, new StringBody(contentType)); entity.addPart(PATH, new StringBody(path)); if (version != null) { entity.addPart(VERSION, new StringBody(version)); } entity.addPart(FILE_UPLOAD, body); post.setEntity(entity); String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); client.getConnectionManager().shutdown(); if (checksumValue != null) { checksumProperties.put(checksumKey, checksumValue); } }
From source file:com.android.volley.toolbox.http.HttpClientStack.java
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws IOException, AuthFailureError { if (request.containsFile()) { /* MultipartEntity multipartEntity = new MultipartEntity(); final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams(); for (String key : multipartParams.keySet()) { multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value)); }// ww w . j a va 2s . c om final Map<String, File> filesToUpload = request.getFilesToUpload(); if(filesToUpload!=null){ for (String key : filesToUpload.keySet()) { File file = filesToUpload.get(key) ; if (file==null || !file.exists()) { throw new IOException(String.format("File not found: %s",file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } multipartEntity.addPart(new FilePart(key, file, null, null)); } } httpRequest.setEntity(multipartEntity); */ MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams(); for (String key : multipartParams.keySet()) { multipartEntity.addPart(key, new StringBody(multipartParams.get(key).value, "text/plain", Charset.forName("UTF-8"))); } final Map<String, File> filesToUpload = request.getFilesToUpload(); if (filesToUpload != null) { for (String key : filesToUpload.keySet()) { File file = filesToUpload.get(key); if (file == null || !file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } multipartEntity.addPart(key, new FileBody(file)); } } httpRequest.setEntity(multipartEntity); } else { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } } }
From source file:org.hyperledger.fabric.sdkintegration.UpdateChannelIT.java
@Test public void setup() { try {// w w w. j av a2 s .c o m //////////////////////////// // Setup client //Create instance of client. HFClient client = HFClient.createNewInstance(); client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite()); //////////////////////////// //Set up USERS //Persistence is not part of SDK. Sample file store is for demonstration purposes only! // MUST be replaced with more robust application implementation (Database, LDAP) File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties"); sampleStoreFile.deleteOnExit(); final SampleStore sampleStore = new SampleStore(sampleStoreFile); //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface //////////////////////////// // get users for all orgs for (SampleOrg sampleOrg : testSampleOrgs) { final String orgName = sampleOrg.getName(); sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName)); } //////////////////////////// //Reconstruct and run the channels SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1"); Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg); // Getting foo channels current configuration bytes. byte[] channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); HttpClient httpclient = HttpClients.createDefault(); // HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/decode/common.Config"); // httppost.setEntity(new ByteArrayEntity(channelConfigurationBytes)); String responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); //responseAsString is JSON but use just string operations for this test. if (!responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { fail(format("Did not find expected batch timeout '%s', in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } //Now modify the batch timeout String updateString = responseAsString.replace(ORIGINAL_BATCH_TIMEOUT, UPDATED_BATCH_TIMEOUT); HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/encode/common.Config"); httppost.setEntity(new StringEntity(updateString)); HttpResponse response = httpclient.execute(httppost); int statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for encoding the new desired channel config bytes", statuscode); assertEquals(200, statuscode); byte[] newConfigBytes = EntityUtils.toByteArray(response.getEntity()); // Now send to configtxlator multipart form post with original config bytes, updated config bytes and channel name. httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/configtxlator/compute/update-from-configs"); HttpEntity multipartEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("original", channelConfigurationBytes, ContentType.APPLICATION_OCTET_STREAM, "originalFakeFilename") .addBinaryBody("updated", newConfigBytes, ContentType.APPLICATION_OCTET_STREAM, "updatedFakeFilename") .addBinaryBody("channel", fooChannel.getName().getBytes()).build(); httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for updated config bytes needed for updateChannelConfiguration ", statuscode); assertEquals(200, statuscode); byte[] updateBytes = EntityUtils.toByteArray(response.getEntity()); UpdateChannelConfiguration updateChannelConfiguration = new UpdateChannelConfiguration(updateBytes); //To change the channel we need to sign with orderer admin certs which crypto gen stores: // private key: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/f1a9a940f57419a18a83a852884790d59b378281347dd3d4a88c2b820a0f70c9_sk //certificate: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem final String sampleOrgName = sampleOrg.getName(); final SampleUser ordererAdmin = sampleStore.getMember(sampleOrgName + "OrderAdmin", sampleOrgName, "OrdererMSP", Util.findFileSk(Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/") .toFile()), Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem") .toFile()); client.setUserContext(ordererAdmin); //Ok now do actual channel update. fooChannel.updateChannelConfiguration(updateChannelConfiguration, client.getUpdateChannelConfigurationSignature(updateChannelConfiguration, ordererAdmin)); Thread.sleep(3000); // give time for events to happen //Let's add some additional verification... client.setUserContext(sampleOrg.getPeerAdmin()); final byte[] modChannelBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, modChannelBytes); if (!responseAsString.contains(UPDATED_BATCH_TIMEOUT)) { //If it doesn't have the updated time out it failed. fail(format("Did not find updated expected batch timeout '%s', in:%s", UPDATED_BATCH_TIMEOUT, responseAsString)); } if (responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { //Should not have been there anymore! fail(format("Found original batch timeout '%s', when it was not expected in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } assertTrue(eventCountFilteredBlock > 0); // make sure we got blockevent that were tested.updateChannelConfiguration assertTrue(eventCountBlock > 0); // make sure we got blockevent that were tested. //Should be no anchor peers defined. assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertFalse(responseAsString.matches(REGX_S_ANCHOR_PEERS)); // Get config update for adding an anchor peer. Channel.AnchorPeersConfigUpdateResult configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers( fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051), null); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getPeersAdded().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); //Now add anchor peer to channel configuration. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); // Check is anchor peer in config block? assertTrue(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // not updating anyting. //Now remove the anchor peer -- get the config update block. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051)); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should still be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer to remove. assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left. // Now do the actual update. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator. channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); // should be gone! assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //ODDLY we still want this even if it's empty! //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().isEmpty()); // peer should be now gone. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left out("That's all folks!"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:rogerthat.topdesk.bizz.Util.java
public static void uploadFile(String apiUrl, String apiKey, String unid, byte[] content, String contentType, String fileName) throws IOException, ParseException { URL url = new URL(apiUrl + "/api/incident/upload/" + unid); HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30)); log.info("Uploading attachment of size " + content.length / 1000 + "KB"); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("filename", content, org.apache.http.entity.ContentType.create(contentType), fileName); addMultipartBodyToRequest(multipartEntityBuilder.build(), request); String authHeader = "TOKEN id=\"" + apiKey + "\""; request.addHeader(new HTTPHeader("Authorization", authHeader)); URLFetchService urlFetch = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = urlFetch.fetch(request); int responseCode = response.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { String responseContent = getContent(response); throw new TopdeskApiException("Uploading image " + fileName + " failed with response code " + responseCode + "\nContent:" + responseContent); }/* w ww . j a v a 2 s. c o m*/ }
From source file:info.ajaxplorer.client.http.RestRequest.java
private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName, AjxpFileBody fileBody) throws Exception { URI originalUri = new URI(uri.toString()); if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) { uri = new URI( uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN())); }//from ww w . j a v a 2 s. c om //Log.d("RestRequest", "Issuing request : " + uri.toString()); HttpResponse response = null; try { HttpRequestBase request; if (postParameters != null || file != null) { request = new HttpPost(); if (file != null) { if (fileBody == null) { if (fileName == null) fileName = file.getName(); fileBody = new AjxpFileBody(file, fileName); ProgressListener origPL = this.uploadListener; Map<String, String> caps = RestStateHolder.getInstance().getServer() .getRemoteCapacities(this); this.uploadListener = origPL; int maxUpload = 0; if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT)) maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT)); maxUpload = Math.min(maxUpload, 60000000); if (maxUpload > 0 && maxUpload < file.length()) { fileBody.chunkIntoPieces(maxUpload); if (uploadListener != null) { uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks()); } } } else { if (uploadListener != null) { uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks()); } } MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("userfile_0", fileBody); if (fileName != null && !EncodingUtils .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) { reqEntity.addPart("urlencoded_filename", new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8"))); } if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) { reqEntity.addPart("appendto_urlencoded_part", new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8"))); } if (postParameters != null) { Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } } if (uploadListener != null) { CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity( reqEntity, uploadListener); ((HttpPost) request).setEntity(countingEntity); } else { ((HttpPost) request).setEntity(reqEntity); } } else { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size()); Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else { request = new HttpGet(); } request.setURI(uri); if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) { request.addHeader("Ajxp-Force-Login", "true"); } response = httpClient.executeInContext(request); if (isAuthenticationRequested(response)) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH); this.discardResponse(response); this.authenticate(); if (loginStateChanged) { // RELOAD loginStateChanged = false; sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA); if (fileBody != null) fileBody.resetChunkIndex(); return this.issueRequest(originalUri, postParameters, file, fileName, fileBody); } } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) { this.discardResponse(response); this.issueRequest(originalUri, postParameters, file, fileName, fileBody); } } catch (ClientProtocolException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } catch (IOException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } catch (AuthenticationException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); throw e; } catch (Exception e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } finally { uploadListener = null; } return response; }
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {/* w w w. j av a 2 s . com*/ try { FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(ApiConstants.ENCODING)); multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()), ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING))); multipartEntity.addPart("file", filebody); multipartEntity.addPart("token", new StringBody(TokenStore.getAccess())); URL url = new URL(uri); HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection(); httpsClient.setRequestMethod("POST"); httpsClient.setDoOutput(true); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength()); } else { httpsClient.setChunkedStreamingMode(0); } httpsClient.setRequestProperty("Connection", "Keep-Alive"); httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + ""); httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION, ApiConstants.BEARER + TokenStore.getAccess()); httpsClient.addRequestProperty(multipartEntity.getContentType().getName(), multipartEntity.getContentType().getValue()); try { OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream()); multipartEntity.writeTo(outputStream); outputStream.flush(); NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode()); } finally { httpsClient.disconnect(); } } catch (DigipostInvalidTokenException e) { OAuth.updateAccessTokenWithRefreshToken(context); uploadFile(context, uri, file); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, context.getString(R.string.error_your_network)); throw new DigipostClientException(context.getString(R.string.error_your_network)); } }
From source file:com.gistlabs.mechanize.requestor.RequestBuilder.java
private HttpPost composeMultiPartFormRequest(final String uri, final Parameters parameters, final Map<String, ContentBody> files) { HttpPost request = new HttpPost(uri); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {/* ww w . j a v a 2s . c om*/ Charset utf8 = Charset.forName("UTF-8"); for (Parameter param : parameters) if (param.isSingleValue()) multiPartEntity.addPart(param.getName(), new StringBody(param.getValue(), utf8)); else for (String value : param.getValues()) multiPartEntity.addPart(param.getName(), new StringBody(value, utf8)); } catch (UnsupportedEncodingException e) { throw MechanizeExceptionFactory.newException(e); } List<String> fileNames = new ArrayList<String>(files.keySet()); Collections.sort(fileNames); for (String name : fileNames) { ContentBody contentBody = files.get(name); multiPartEntity.addPart(name, contentBody); } request.setEntity(multiPartEntity); return request; }