List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java
/** {@inheritDoc} */ @Override// w w w . j av a2 s .c om public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener) throws QQException { try { URI uri = URI.create(request.getUrl()); if (request.getMethod().equals("POST")) { HttpPost httppost = new HttpPost(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout()); } if (request.getFileMap().size() > 0) { MultipartEntity entity = new MultipartEntity(); String charset = request.getCharset(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; entity.addPart(key, new StringBody(value, Charset.forName(charset))); } Map<String, File> fileMap = request.getFileMap(); for (String key : fileMap.keySet()) { File value = fileMap.get(key); entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value)))); } httppost.setEntity(entity); } else if (request.getPostMap().size() > 0) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; list.add(new BasicNameValuePair(key, value)); } httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset())); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httppost.addHeader(key, headerMap.get(key)); } QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener); QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar); QQHttpResponseCallback callback = new QQHttpResponseCallback(listener); Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback); return new ProxyFuture(future, consumer, producer); } else if (request.getMethod().equals("GET")) { HttpGet httpget = new HttpGet(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httpget.addHeader(key, headerMap.get(key)); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout()); } return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget), new QQHttpResponseConsumer(request, listener, cookieJar), new QQHttpResponseCallback(listener)); } else { throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod()); } } catch (IOException e) { throw new QQException(QQErrorCode.IO_ERROR); } }
From source file:org.ubicompforall.BusTUC.Speech.HTTP.java
public DummyObj sendPost(String filePath, Context context, double lat, double lon) { String response = "Fant ikke noe"; long first = System.nanoTime(); Calc calc = new Calc(); DummyObj dummy = new DummyObj(); HttpClient httpclient = new DefaultHttpClient(); long second = System.nanoTime() - first; // File file = new File(Environment.getExternalStorageDirectory(), // filePath); File file = new File(filePath); HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst"); final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String t_id = tm.getDeviceId(); String tmp = "TABuss"; String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); try {/*from ww w . j a v a 2 s . c o m*/ MultipartEntity entity = new MultipartEntity(); entity.addPart("lat", new StringBody(String.valueOf(lat))); entity.addPart("lon", new StringBody(String.valueOf(lon))); entity.addPart("devID", new StringBody(tmp + p_id)); entity.addPart("speechinput", new FileBody(file, "multipart/form-data;charset=\"UTF-8\"")); httppost.setEntity(entity); response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8"); System.out.println("RESPONSE: " + response); dummy = calc.parse(response); } catch (ClientProtocolException e) { } catch (IOException e) { } return dummy; }
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 www . jav a 2 s.c o 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.vmware.photon.controller.client.RestClient.java
public HttpResponse upload(String path, String inputFileName, Map<String, String> arguments) throws IOException { HttpClient client = getHttpClient(); HttpPost httppost = new HttpPost(target + path); File file = new File(inputFileName); if (sharedSecret != null) { httppost.addHeader(AUTHORIZATION_HEADER, AUTHORIZATION_METHOD + sharedSecret); }//from w w w.ja va2s. co m MultipartEntity mpEntity = new MultipartEntity(); FileBody cbFile = new FileBody(file, "application/octect-stream"); for (Map.Entry<String, String> argument : arguments.entrySet()) { StringBody stringBody = new StringBody(argument.getValue()); mpEntity.addPart(argument.getKey(), stringBody); } mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); return client.execute(httppost); }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type HowTo And" + " Source File through the publisher rest API ", dependsOnMethods = "testApiCreation") public void testAddDocumentToAnAPIHowToFile() throws Exception { String fileNameAPIM614 = "APIM614.txt"; String docName = "APIM614PublisherTestHowTo-File-summary"; String docType = "How To"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM614 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM614; ;/* w w w .j a va 2s. c om*/ 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(filePathAPIM614); 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 "); }
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 a2 s. c om 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: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. j av a2s . co m } 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:net.rcarz.jiraclient.RestClient.java
private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments) throws RestException, IOException { if (attachments != null) { req.setHeader("X-Atlassian-Token", "nocheck"); MultipartEntity ent = new MultipartEntity(); for (Issue.NewAttachment attachment : attachments) { String filename = attachment.getFilename(); Object content = attachment.getContent(); if (content instanceof byte[]) { ent.addPart("file", new ByteArrayBody((byte[]) content, filename)); } else if (content instanceof InputStream) { ent.addPart("file", new InputStreamBody((InputStream) content, filename)); } else if (content instanceof File) { ent.addPart("file", new FileBody((File) content, filename)); } else if (content == null) { throw new IllegalArgumentException("Missing content for the file " + filename); } else { throw new IllegalArgumentException( "Expected file type byte[], java.io.InputStream or java.io.File but provided " + content.getClass().getName() + " for the file " + filename); }// w w w . j a v a2 s .c om } req.setEntity(ent); } return request(req); }
From source file:no.digipost.android.api.ApiAccess.java
public static void uploadFile(Context context, String uri, File file) throws DigipostClientException { try {//w ww . j a v a2 s .c om 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 va 2 s. co m 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); } }