List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:interactivespaces.util.web.HttpClientHttpContentCopier.java
/** * Perform the actual content copy./*from ww w . j a va 2 s.co m*/ * * @param destinationUri * URI for the destination * @param sourceParameterName * the parameter name in the HTTP form post for the content * @param params * the parameters to be included, can be {@code null} * @param contentBody * the content to be sent */ private void doCopyTo(String destinationUri, String sourceParameterName, Map<String, String> params, AbstractContentBody contentBody) { HttpEntity entity = null; try { HttpPost httpPost = new HttpPost(destinationUri); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart(sourceParameterName, contentBody); if (params != null) { for (Entry<String, String> entry : params.entrySet()) { mpEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } } httpPost.setEntity(mpEntity); HttpResponse response = httpClient.execute(httpPost); entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new SimpleInteractiveSpacesException( String.format("Server returned bad status code %d for source URI %s during HTTP copy", statusCode, destinationUri)); } } catch (InteractiveSpacesException e) { throw e; } catch (Exception e) { throw new InteractiveSpacesException( String.format("Could not send file to destination URI %s during HTTP copy", destinationUri), e); } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { throw new InteractiveSpacesException(String .format("Could not consume entity content for %s during HTTP copy", destinationUri), e); } } } }
From source file:com.dropbox.client.DropboxClient.java
/** * Put a file in the user's Dropbox./*from w ww .j a v a 2s . c om*/ */ public HttpResponse putFile(String root, String to_path, File file_obj) throws DropboxException { String path = "/files/" + root + to_path; HttpClient client = getClient(); try { String target = buildFullURL(secureProtocol, content_host, this.port, buildURL(path, API_VERSION, null)); HttpPost req = new HttpPost(target); // this has to be done this way because of how oauth signs params // first we add a "fake" param of file=path of *uploaded* file // THEN we sign that. List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("file", file_obj.getName())); req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); consumer.sign(req); // now we can add the real file multipart and we're good MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody bin = new FileBody(file_obj); entity.addPart("file", bin); // this resets it to the new entity with the real file req.setEntity(entity); HttpResponse resp = client.execute(req); resp.getEntity().consumeContent(); return resp; } catch (Exception e) { throw new DropboxException(e); } }
From source file:sjizl.com.FileUploadTest2.java
private void doFileUpload() { String username = ""; String password = ""; String foto = ""; String foto_num = ""; SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE); username = sp.getString("username", null); password = sp.getString("password", null); foto = sp.getString("foto", null); foto_num = sp.getString("foto_num", null); File file1 = new File(selectedPath1); String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password=" + password;/* w ww.ja v a 2 s . c om*/ try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); FileBody bin1 = new FileBody(file1); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("uploadedfile1", bin1); reqEntity.addPart("user", new StringBody("User")); post.setEntity(reqEntity); HttpResponse response = client.execute(post); resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE", response_str); runOnUiThread(new Runnable() { public void run() { try { res.setTextColor(Color.GREEN); res.setText("n Response from server : n " + response_str); CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest2.this, "Upload Complete! ", null, R.drawable.iconbd); Brows(); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } //RegisterActivity.login(username,password,getApplicationContext()); }
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Updates a dialog./*from w w w . j a v a 2 s. c om*/ * * @param dialogId The dialog identifier * @param dialogFile The dialog file * @return the created dialog * @throws UnsupportedEncodingException * @see Dialog */ public Dialog updateDialog(final String dialogId, final File dialogFile) throws UnsupportedEncodingException { if (dialogId == null || dialogId.isEmpty()) throw new IllegalArgumentException("dialogId can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); HttpRequestBase request = Request.Put("/v1/dialogs/" + dialogId).withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ executeWithoutResponse(request); Dialog dialog = new Dialog().withDialogId(dialogId); return dialog; }
From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java
@Override public void processNZB(NZB nzb) throws RetrieveException { try {//from www . j ava 2 s . c o m login(); List<NameValuePair> fields = null; String command = null; if (useReportId(nzb)) { fields = getReportIdProps(nzb); command = getReportIdCommand(); } else if (useUrl(nzb)) { fields = getUrlProps(nzb); command = getUrlCommand(); } if (fields != null) { //Do the request HttpResponse response = null; try { response = doGet(command, fields); validateResponse(response.getEntity().getContent()); } finally { if (response != null) { response.getEntity().consumeContent(); } } } else { // no url or reportId //post file using POST fields = getFilepostOtherProps(nzb); command = getFilepostCommand(); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cb = new InputStreamBody(new ByteArrayInputStream(nzb.getData()), nzb.getFilename()); entity.addPart(getFilepostField(), cb); HttpResponse response = null; try { response = doPost(command, fields, entity); validateResponse(response.getEntity().getContent()); } finally { if (response != null) { response.getEntity().consumeContent(); } } } logout(); } catch (IOException e) { throw new RetrieveException("Error posting nzb file", e); } }
From source file:com.cianmcgovern.android.ShopAndShare.Share.java
/** * Uploads the text file specified by filename * // w w w. ja va 2 s. c o m * @param instance * The results instance to use * @param location * The location as specified by the user * @param store * The store as specified by the user * @return Response message from server * @throws ClientProtocolException * @throws IOException */ private String upload(Results instance, String location, String store) throws ClientProtocolException, IOException { Log.v(Constants.LOG_TAG, "Inside upload"); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String filename = Results.getInstance().toFile(); HttpPost httpPost = new HttpPost(Constants.FULL_URL); File file = new File(filename); MultipartEntity entity = new MultipartEntity(); ContentBody cb = new FileBody(file, "plain/text"); entity.addPart("inputfile", cb); ContentBody cbLocation = new StringBody(location); entity.addPart("location", cbLocation); ContentBody cbStore = new StringBody(store); entity.addPart("store", cbStore); httpPost.setEntity(entity); Log.v(Constants.LOG_TAG, "Sending post"); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String message = EntityUtils.toString(resEntity); Log.v(Constants.LOG_TAG, "Response from upload is: " + message); resEntity.consumeContent(); httpClient.getConnectionManager().shutdown(); file.delete(); return message; }
From source file:com.alibaba.openapi.client.rpc.AbstractHttpRequestBuilder.java
public HttpRequest getHttpRequest(InvokeContext context) { final RequestPolicy requestPolicy = context.getPolicy(); final StringBuilder path = getProtocolRequestPath(context, getProtocol()); final StringBuilder queryString = new StringBuilder(); final String method; final List<NameValuePair> parameters = buildParams(context); buildSysParams(parameters, queryString, context, requestPolicy); HttpEntity entity = null;/* w w w . j ava 2s . c o m*/ switch (requestPolicy.getHttpMethod()) { case POST: method = METHOD_POST; break; case GET: method = METHOD_GET; break; case AUTO: if (hasParameters(parameters) || hasAttachments(context.getRequest())) { method = METHOD_POST; } else { method = METHOD_GET; } break; default: method = METHOD_POST; } if (hasParameters(parameters)) { if (METHOD_GET.equals(method)) { if (queryString.length() > 0) { queryString.append(PARAMETER_SEPARATOR); } queryString.append(URLEncodedUtils.format(parameters, requestPolicy.getQueryStringCharset())); } else { try { entity = new UrlEncodedFormEntity(parameters, requestPolicy.getContentCharset()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } } signature(path, queryString, parameters, requestPolicy); HttpRequest httpRequest; try { httpRequest = requestFactory.newHttpRequest(method, getApiRequestPath(context, requestPolicy) .append('/').append(path).append(QUERY_STRING_SEPARATOR).append(queryString).toString()); } catch (MethodNotSupportedException e) { throw new UnsupportedOperationException("Unsupported http request method:" + e.getMessage(), e); } if (httpRequest instanceof BasicHttpEntityEnclosingRequest) { if (hasAttachments(context.getRequest())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Entry<String, String> entry : context.getRequest().getAttachments().entrySet()) { File file = new File(entry.getValue()); multipartEntity.addPart(entry.getKey(), new FileBody(file)); } entity = multipartEntity; } else if (requestPolicy.getRequestCompressThreshold() >= 0 && entity.getContentLength() > requestPolicy.getRequestCompressThreshold()) { entity = new GzipCompressingNEntity(entity); httpRequest.addHeader("Content-Encoding", "gzip"); } ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity); } // httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // httpRequest.addHeader("Accept-Charset", "gb18030,utf-8;q=0.7,*;q=0.3"); // httpRequest.addHeader("Accept-Encoding", "gzip,deflate,sdch"); // httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.8"); // httpRequest.addHeader("Cache-Control", "max-age=0"); // httpRequest.addHeader("Connection", "keep-alive"); return httpRequest; }
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Creates a dialog.//from w w w . j av a2 s . co m * * @param name The dialog name * @param dialogFile The dialog file created by using the Dialog service Applet. * @return The created dialog * @see Dialog */ public Dialog createDialog(final String name, final File dialogFile) { if (name == null || name.isEmpty()) throw new IllegalArgumentException("name can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); reqEntity.addPart("name", new StringBody(name, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post("/v1/dialogs").withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ HttpResponse response = execute(request); return ResponseUtil.getObject(response, Dialog.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:jp.tonyu.soytext2.file.Comm.java
public Scriptable execMultiPart(String rootPath, String relPath, final Scriptable sparams, Object responseType) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(rootPath + relPath); final MultipartEntity reqEntity = new MultipartEntity(); Scriptables.each(sparams, new StringPropAction() { @Override/*from w ww. ja v a2 s .c o m*/ public void run(String key, Object value) { if (value instanceof String) { String s = (String) value; try { reqEntity.addPart(key, new StringBody(s, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String filename = (String) ScriptableObject.getProperty(s, FileUpload.FILENAME); Object body = ScriptableObject.getProperty(s, FileUpload.BODY); InputStream st = null; if (body instanceof InputStream) { st = (InputStream) body; } else if (body instanceof ReadableBinData) { ReadableBinData rbd = (ReadableBinData) body; try { st = rbd.getInputStream(); } catch (IOException e) { Log.die(e); } } if (st == null) throw new RuntimeException("Not a bindata - " + body); InputStreamBody bin = new InputStreamBody(st, filename); reqEntity.addPart(key, bin); } } }); httppost.setEntity(reqEntity); Log.d(this, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); Scriptable res = response2Scriptable(response, responseType); return res; }