List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:net.dahanne.gallery3.client.business.G3Client.java
private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs, String requestMethod, File file) throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException { HttpClient defaultHttpClient = new DefaultHttpClient(); HttpRequestBase httpMethod;/*w w w . j av a 2 s .c om*/ //are we using rewritten urls ? if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) { appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php"); } logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl); if (POST.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1); StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8")); multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("file", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } else { ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else if (PUT.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else if (DELETE.equals(requestMethod)) { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); //this is to avoid the HTTP 414 (length too long) error //it should only happen when getting items, index.php/rest/items?urls= // } else if(appendToGalleryUrl.length()>2000) { // String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?")); // String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("=")); // String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1); // httpMethod = new HttpPost(galleryItemUrl + resource); // httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); // nameValuePairs.add(new BasicNameValuePair(variable, value)); // ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity( // nameValuePairs)); } else { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); } if (existingApiKey != null) { httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey); } //adding the userAgent to the request httpMethod.setHeader(USER_AGENT, userAgent); HttpResponse response = null; String[] patternsArray = new String[3]; patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z"; patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z"; patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z"; try { // be extremely careful here, android httpclient needs it to be // an // array of string, not an arraylist defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray); response = defaultHttpClient.execute(httpMethod); } catch (ClassCastException e) { List<String> patternsList = Arrays.asList(patternsArray); defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList); response = defaultHttpClient.execute(httpMethod); } int responseStatusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = null; if (response.getEntity() != null) { responseEntity = response.getEntity(); } switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_MOVED_TEMP: //the gallery is using rewritten urls, let's remember it and re hit the server this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new G3BadRequestException(); case HttpURLConnection.HTTP_FORBIDDEN: //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url if (appendToGalleryUrl.contains(INDEX_PHP_REST)) { this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; } throw new G3ForbiddenException(); case HttpURLConnection.HTTP_NOT_FOUND: throw new G3ItemNotFoundException(); default: throw new G3GalleryException("HTTP code " + responseStatusCode); } return responseEntity; }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static HttpUriRequest createUploadFileToServerRequest(String URL, String userName, final String fileName) { HttpPost request = new HttpPost(URL); String path = fileName;/* w ww . j a v a 2s . c o m*/ if (URL.indexOf("deletefile") == -1) {//$NON-NLS-1$ if (URL.indexOf("deployjob") != -1) {//$NON-NLS-1$ path = URL.substring(URL.indexOf("=") + 1);//$NON-NLS-1$ } MultipartEntity entity = new MultipartEntity(); entity.addPart(path, new FileBody(new File(fileName))); request.setEntity(entity); } addStudioToken(request, userName); return request; }
From source file:net.dahanne.gallery.g2.java.client.business.G2Client.java
private MultipartEntity createMultiPartEntityForSendImageToGallery(int albumName, File imageFile, String imageName, String summary, String description) throws GalleryConnectionException { if (imageName == null) { imageName = imageFile.getName().substring(0, imageFile.getName().indexOf(".")); }/*from ww w . j a v a2 s . com*/ MultipartEntity multiPartEntity; try { multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("g2_controller", new StringBody("remote.GalleryRemote", UTF_8)); multiPartEntity.addPart("g2_form[cmd]", new StringBody("add-item", UTF_8)); multiPartEntity.addPart("g2_form[set_albumName]", new StringBody("" + albumName, UTF_8)); if (authToken != null) { multiPartEntity.addPart("g2_authToken", new StringBody(authToken, UTF_8)); } multiPartEntity.addPart("g2_form[caption]", new StringBody(imageName, UTF_8)); multiPartEntity.addPart("g2_form[extrafield.Summary]", new StringBody(summary, UTF_8)); multiPartEntity.addPart("g2_form[extrafield.Description]", new StringBody(description, UTF_8)); multiPartEntity.addPart("g2_userfile", new FileBody(imageFile)); } catch (Exception e) { throw new GalleryConnectionException(e.getMessage()); } return multiPartEntity; }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Posts a <tt>file</tt> to the <tt>address</tt>. * @param address the address to post the form to. * @param fileParamName the name of the param for the file. * @param file the file we will send.//from w w w .j a va2s .c o m * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @return the result or null if send was not possible or * credentials ask if any was canceled. */ public static HTTPResponseResult postFile(String address, String fileParamName, File file, String usernamePropertyName, String passwordPropertyName) { DefaultHttpClient httpClient = null; try { HttpPost postMethod = new HttpPost(address); httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, postMethod.getURI().getHost(), null); String mimeType = URLConnection.guessContentTypeFromName(file.getPath()); if (mimeType == null) mimeType = "application/octet-stream"; FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(fileParamName, bin); postMethod.setEntity(reqEntity); HttpEntity resEntity = executeMethod(httpClient, postMethod, null, null); if (resEntity == null) return null; return new HTTPResponseResult(resEntity, httpClient); } catch (Throwable e) { logger.error("Cannot post file to:" + address, e); } return null; }
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 w w w.j av a2 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:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u//from w w w . j ava2 s. c o m * @param data * @param name * @param contentType * @return */ public HttpResponseBean uploadFile(String u, InputStream data, String name, String contentType) { Map<String, Object> headers = new HashMap<String, Object>(); u = getURL(u, null); HttpPost post = new HttpPost(u); try { MultipartEntity request = new MultipartEntity(); ContentBody body = new InputStreamBody(data, contentType, name); request.addPart("file", body); post.setEntity(request); for (String h : headers.keySet()) { post.setHeader(h, "" + headers.get(h)); } client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser"); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY); HttpResponse resp = null; try { resp = client.execute(host, post, context); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } Map<String, String> rh = new HashMap<String, String>(); for (Header h : resp.getAllHeaders()) { rh.put(h.getName(), h.getValue()); } try { HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh, EntityUtils.toByteArray(resp.getEntity())); printIfError(u, r); return r; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } finally { post.releaseConnection(); } }
From source file:bluej.collect.DataCollectorImpl.java
public static void projectOpened(Project proj, List<ExtensionWrapper> projectExtensions) { MultipartEntity mpe = new MultipartEntity(); addExtensions(mpe, projectExtensions); submitEventNoData(proj, null, EventName.PROJECT_OPENING); }
From source file:org.deviceconnect.android.profile.restful.test.StressTestCase.java
private HttpUriRequest createFileSendRequest() throws IOException { final String name = "test.png"; URIBuilder builder = TestURIBuilder.createURIBuilder(); builder.setProfile(FileProfileConstants.PROFILE_NAME); builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND); builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()); builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/test.png"); AssetManager manager = getApplicationContext().getAssets(); InputStream in = null;// w w w . ja va2 s. c o m try { MultipartEntity entity = new MultipartEntity(); in = manager.open(name); // ?? ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] buf = new byte[BUF_SIZE]; while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } // ? entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name)); HttpPost request = new HttpPost(builder.toString()); request.setEntity(entity); return request; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
From source file:palamarchuk.smartlife.app.fragments.ProfileFragment.java
private void attachCardQuery(String cardNumber, String cardPin) { final QueryMaster.OnCompleteListener onCompleteListener = new QueryMaster.OnCompleteListener() { @Override//from w ww .j a va2 s .c o m public void complete(String serverResponse) { // QueryMaster.alert(getActivity(), serverResponse); try { JSONObject json = new JSONObject(serverResponse); if (QueryMaster.isSuccess(json)) { FragmentHelper.updateFragment(getFragmentManager()); QueryMaster.alert(getActivity(), R.string.bonuses_was_added_from_card); } else { QueryMaster.toast(getActivity(), json.getString("message")); } } catch (JSONException e) { e.printStackTrace(); QueryMaster.alert(getActivity(), QueryMaster.SERVER_RETURN_INVALID_DATA); } } @Override public void error(int errorCode) { QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE); } }; MultipartEntity entity = new MultipartEntity(); try { entity.addPart("card_number", new StringBody(cardNumber)); entity.addPart("pin", new StringBody(cardPin)); entity.addPart("token", new StringBody(((FragmentHolderActivity) getActivity()).getDeviceToken())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } QueryMaster queryMaster = new QueryMaster(getActivity(), ServerRequest.ATTACH_CARD, QueryMaster.QUERY_POST, entity); queryMaster.setProgressDialog(); queryMaster.setOnCompleteListener(onCompleteListener); queryMaster.start(); }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Sample SDK And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIHowToFile") public void testAddDocumentToAnAPISDKToFile() throws Exception { String fileNameAPIM622 = "APIM622.txt"; String docName = "APIM622PublisherTestHowTo-File-summary"; String docType = "samples"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM622 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM622; String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM622); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }