List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, final String mimeType, Charset charset) throws UnsupportedEncodingException
From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java
private static MultipartEntity getMultipartEntity(HttpServletRequest request) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String value = request.getParameter(name); try {//from ww w. j av a 2s . c om if (name.equals("file")) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10000000);// 10 Mo List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(item.getName()); FileOutputStream fos = new FileOutputStream(file); fos.write(item.get()); fos.flush(); fos.close(); entity.addPart(name, new FileBody(file, "application/zip")); } } else { entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileUploadException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return entity; }
From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java
@Test public void testFileUploadWithEagerParsingAndNonASCIIFilename() throws Exception { DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler())); TestHttpClient client = new TestHttpClient(); try {//from w ww . j a va2 s. c o m HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path"); MultipartEntity entity = new MultipartEntity(); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); File uploadfile = new File( MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()); FormBodyPart filePart = new FormBodyPart("file", new FileBody(uploadfile, "", "application/octet-stream", Charsets.UTF_8.toString())); filePart.addField("Content-Disposition", "form-data; name=\"file\"; filename*=\"utf-8''%CF%84%CE%B5%CF%83%CF%84.txt\""); entity.addPart(filePart); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequestToLarge() throws IOException { TestHttpClient client = new TestHttpClient(); try {//from ww w .ja va2 s. c o m 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:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {/*from ww w . j av a2 s.co m*/ HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URI url_orig; try { url_orig = new URI(url_string); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = url_orig.getHost(), authority = url_orig.getAuthority(); final String resolved_host = resolver != null ? resolver.resolve(host) : null; final String resolved_url = !isEmpty(resolved_host) ? url_string.replace("://" + host, "://" + resolved_host) : url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter parameter : params) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : params) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new TwitterException("Unsupported request method " + req.getMethod()); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (!isEmpty(resolved_host) && !resolved_host.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
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)); }/*from ww w. j a va 2s .c o m*/ 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:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {// w ww. ja v a2s .co m 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.dwdesign.tweetings.util.httpclient.HttpClientImpl.java
@Override public twitter4j.internal.http.HttpResponse request(final twitter4j.internal.http.HttpRequest req) throws TwitterException { try {/*from w w w .ja v a 2s . com*/ HttpRequestBase commonsRequest; //final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URL url_orig = new URL(url_string); final String host = url_orig.getHost(); //final String resolved_host = resolver != null ? resolver.resolve(host) : null; //final String resolved_url = resolved_host != null ? url_string.replace("://" + host, "://" + resolved_host) // : url_string; final String resolved_url = url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; if (req.getParameters() != null) { for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { final ArrayList<NameValuePair> args = new ArrayList<NameValuePair>(); for (final HttpParameter parameter : req.getParameters()) { args.add(new BasicNameValuePair(parameter.getName(), parameter.getValue())); } if (args.size() > 0) { post.setEntity(new UrlEncodedFormEntity(args, "UTF-8")); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new AssertionError(); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } //if (resolved_host != null && !host.equals(resolved_host)) { //commonsRequest.addHeader("Host", host); //} final ApacheHttpClientHttpResponseImpl res = new ApacheHttpClientHttpResponseImpl( client.execute(commonsRequest), conf); final int statusCode = res.getStatusCode(); if (statusCode < OK && statusCode > ACCEPTED) throw new TwitterException(res.asString(), res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {//from w w w. j a v a 2 s. c o m HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String urlString = req.getURL(); final URI urlOrig; try { urlOrig = new URI(urlString); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGet(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPost post = new HttpPost(resolvedUrl); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter param : params) { if (param.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), param.getContentType()); } else { body = new InputStreamBody(param.getFileBody(), param.getFileName(), param.getContentType()); } me.addPart(param.getName(), body); } else { final ContentBody body = new StringBody(param.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(param.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolvedUrl); } else if (method == RequestMethod.PUT) { commonsRequest = new HttpPut(resolvedUrl); } else throw new TwitterException("Unsupported request method " + method); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java
private void constructMultipartRequest(HttpEntityEnclosingRequestBase httpRequest, String requestBody, String mediaType, List<RestAttachment> attachments) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); if (requestBody != null) { multipartEntity.addPart("payload", new StringBody(requestBody, mediaType, Charset.forName("UTF-8"))); }/* w ww. j a v a 2 s .c o m*/ int attachmentCount = 0; for (RestAttachment attachment : attachments) { String attachmentName = "attachment" + (++attachmentCount); multipartEntity.addPart(attachmentName, new ByteArrayBody(attachment.getBinaryContent(), attachment.getMediaType(), attachmentName)); } httpRequest.setEntity(multipartEntity); }
From source file:com.iia.giveastick.util.RestClient.java
private HttpEntity buildMultipartEntity(JSONObject jsonParams) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {//w ww .j a va2s . co m String path = jsonParams.getString("file"); if (debugWeb && GiveastickApplication.DEBUG) { Log.d(TAG, "key : file value :" + path); } if (!TextUtils.isEmpty(path)) { // File entry File file = new File(path); FileBody fileBin = new FileBody(file, "application/octet"); entity.addPart("file", fileBin); try { entity.addPart("file", new StringBody(path, "text/plain", Charset.forName(HTTP.UTF_8))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return entity; }