List of usage examples for org.apache.http.entity.mime MultipartEntity getContentType
public Header getContentType()
From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java
private void setMultipartEntity(HootRequest request, HttpURLConnection connection) throws IOException { OutputStream os = null;/*from w w w .ja va2 s . c o m*/ MultipartEntity entity = request.getMultipartEntity(); try { connection.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue()); os = new BufferedOutputStream(connection.getOutputStream(), (int) request.getMultipartEntity().getContentLength()); entity.writeTo(os); } finally { if (os != null) { try { os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:org.ez.flickr.api.FlickrService.java
final <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz, String url) throws FlickrException { try {/*from ww w.j a v a2 s. c om*/ OAuthRequest request = new OAuthRequest(Verb.POST, url); // check for proxy, use if available if (proxy != null) { // request.setProxy(proxy); } for (Map.Entry<String, Object> param : args.getParameters().entrySet()) { if (param.getValue() instanceof String) { request.addQuerystringParameter(param.getKey(), (String) param.getValue()); } } oauth.signRequest(request); MultipartEntity multipart = args.getBody(request.getOauthParameters()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); request.addPayload(baos.toByteArray()); request.addHeader("Content-type", multipart.getContentType().getValue()); Response response = request.send(); String body = response.getBody(); return parseBody(args, clazz, body); } catch (IOException ex) { throw new UnsupportedOperationException("Error preparing multipart request", ex); } }
From source file:org.wso2.am.integration.tests.other.InvalidAuthTokenLargePayloadTestCase.java
/** * Upload a file to the given URL/* w ww . ja v a 2 s.c o m*/ * * @param endpointUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private HttpResponse uploadFile(String endpointUrl, File fileName, Map<String, String> headers) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(endpointUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); //setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { connection.setRequestProperty(key, headers.get(key)); } } for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } } OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder responseMsg = new StringBuilder(); while ((temp = read.readLine()) != null) { responseMsg.append(temp); } HttpResponse response = new HttpResponse(responseMsg.toString(), status); return response; }
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input, String fileName, String mimeType) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;//from www . j a v a 2 s .co m if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml) : null; HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntity requestMultipartEntity = new MultipartEntity(); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept", "application/xml"); // add xml part to the multipart entity if (xml != null) { //StringBody xmlPart = new StringBody( // xml, "application/xml; name=body.xml", Charset.forName( getEncoding() ) ); InputStreamBody xmlPart = new InputStreamBody(new ByteArrayInputStream(xml.getBytes(getEncoding())), "application/xml", "body.xml"); requestMultipartEntity.addPart("metadata", xmlPart); } // add file part to the multipart entity if (input != null) { mimeType = StringUtils.trimToNull(mimeType); if (mimeType == null) mimeType = "application/octet-stream"; fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; InputStreamBody filePart = new InputStreamBody(input, mimeType, fileName); requestMultipartEntity.addPart("attachment", filePart); } // add multipart entity to the request ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request getAuthConsumer().sign(request); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java
@Override public HashSet<Tag> solveC2W(String text) throws AnnotationException { lastTime = Calendar.getInstance().getTimeInMillis(); HashSet<Tag> res = new HashSet<Tag>(); try {// w w w .ja v a 2s .c om URL erdApi = new URL(url); HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("runID", new StringBody(this.run)); multipartEntity.addPart("TextID", new StringBody("" + text.hashCode())); multipartEntity.addPart("Text", new StringBody(text)); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = ((HttpURLConnection) connection).getResponseCode(); if (status != 200) { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String line = null; while ((line = br.readLine()) != null) System.err.println(line); throw new RuntimeException(); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = br.readLine()) != null) { String mid = line.split("\t")[2]; String title = freebApi.midToTitle(mid); int wid; if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1) System.err.println("Discarding mid=" + mid); else res.add(new Tag(wid)); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } lastTime = Calendar.getInstance().getTimeInMillis() - lastTime; return res; }
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input, String fileName, final long fileSize) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;/* w ww .j a va 2 s . c o m*/ if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntity requestMultipartEntity = new MultipartEntity(); request.setHeader("MIME-Version", "1.0"); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept-Charset", "UTF-8"); request.setHeader("Accept-Encoding", "gzip,deflate"); request.setHeader("Connection", "close"); // add auth part to the multipart entity auth = StringUtils.trimToNull(auth); if (auth != null) { StringBody authPart = new StringBody(auth, Charset.forName(getEncoding())); requestMultipartEntity.addPart("auth", authPart); } // add file part to the multipart entity if (input != null) { fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; //InputStreamBody filePart = new InputStreamBody( input, fileName ); InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize); requestMultipartEntity.addPart("videofile", filePart); } // add multipart entity to the request ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request //getAuthConsumer().sign( request ); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(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:org.wso2.am.integration.tests.other.APIImportExportTestCase.java
/** * Upload a file to the given URL// w w w.j a v a 2 s .com * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); }
From source file:androhashcheck.MainFrame.java
/** * Upolads file on server for given path as a String. * * @param fileName/*from ww w . jav a 2 s . c o m*/ */ public void upoloadFile(String fileName) { try { String url = ConfigClass.serverURL + "/api/upload_task"; URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(new File(fileName)); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty("token", ConfigClass.token); try (OutputStream out = connection.getOutputStream()) { multipartEntity.writeTo(out); } int status = connection.getResponseCode(); System.out.println(status); System.out.println(connection.getResponseMessage()); StringBuilder response; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } updateStatus(fileName + " done uploading, server response: " + response); if (status == 200) { shouldCheckTasks = true; String taskId = response.toString().replace("}", "").split(":")[1].trim(); TaskObject newTask = new TaskObject(); newTask.setFileName(fileName); newTask.setTaskId(taskId); taskList.add(newTask); } } catch (Exception ex) { updateStatus("error with uploading " + fileName); Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.coronastreet.gpxconverter.GarminForm.java
public void upload() { httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { try {/*w w w . j av a 2 s . c o m*/ HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#"); HttpResponse formResponse = httpClient.execute(get, localContext); HttpEntity formEntity = formResponse.getEntity(); EntityUtils.consume(formEntity); HttpPost request = new HttpPost( "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx"); request.setHeader("Referer", "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1"); request.setHeader("Accept", "text/html, application/xhtml+xml, */*"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); output = "[" + output + "]"; //OMG Garmin Sucks at JSON..... JSONObject uploadResponse = new JSONArray(output).getJSONObject(0); JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult"); try { int uploadID = importResult.getInt("uploadId"); log("Success! UploadID is " + uploadID); } catch (Exception e) { JSONArray failures = (JSONArray) importResult.get("failures"); JSONObject failure = (JSONObject) failures.get(0); JSONArray errorMessages = failure.getJSONArray("messages"); JSONObject errorMessage = errorMessages.getJSONObject(0); String content = errorMessage.getString("content"); log("Upload Failed! Error: " + content); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }