List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity(final HttpMultipartMode mode)
From source file:cl.nic.dte.net.ConexionSii.java
private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII, String token, String urlEnvio, String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(urlEnvio); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2))); reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length()))); reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2))); reqEntity.addPart("dvCompany", new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length()))); FileBody bin = new FileBody(archivoEnviarSII); reqEntity.addPart("archivo", bin); httppost.setEntity(reqEntity);// w w w . j av a 2 s . c om BasicClientCookie cookie = new BasicClientCookie("TOKEN", token); cookie.setPath("/"); cookie.setDomain(hostEnvio); cookie.setSecure(true); cookie.setVersion(1); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE"))); HttpResponse response = httpclient.execute(httppost, localContext); HttpEntity resEntity = response.getEntity(); RECEPCIONDTEDocument resp = null; HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/SiiDte"); XmlOptions opts = new XmlOptions(); opts.setLoadSubstituteNamespaces(namespaces); resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts); return resp; }
From source file:com.groupon.odo.bmp.http.BrowserMobHttpRequest.java
public void makeMultiPart() { if (!multiPart) { multiPart = true;/*ww w . j av a 2 s . c o m*/ multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); } }
From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java
public static String getIdFromFileUploader(String url, List<NameValuePair> params) throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException, JSONException {//from w ww . ja va 2 s . co m // Making HTTP request // defaultHttpClient HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); HttpClient httpClient = new DefaultHttpClient(httpParams); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("database", Const.DATABASE); Charset charSet = Charset.forName("UTF-8"); // Setting up the // encoding MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) { // If the key equals to "file", we use FileBody to // transfer the data entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); } else { // Normal string data entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet)); } } httpPost.setEntity(entity); print(httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); // if (httpResponse.getStatusLine().getStatusCode() > 400) // { // if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent())); // throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); // } // BufferedReader reader = new BufferedReader(new // InputStreamReader(is, "iso-8859-1"), 8); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); String json = sb.toString(); Logger.debug("RESPONSE", json); return json; }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java
protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException { SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH;//from w w w . j av a 2 s . co m } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } String basePath = baseUrl; if (collection != null) basePath += "/" + collection; if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } return new HttpGet(basePath + path + wparams.toQueryString()); } if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) { String url = basePath + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName; LinkedList<NameValuePair> postOrPutParams = new LinkedList<>(); if (streams == null || isMultipart) { // send server list and request list as query string params ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams); queryParams.add(calculateQueryParams(request.getQueryParams(), wparams)); String fullQueryUrl = url + queryParams.toQueryString(); HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl); if (!isMultipart) { postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<>(); Iterator<String> iter = wparams.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = wparams.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8))); } else { postOrPutParams.add(new BasicNameValuePair(p, v)); } } } } // TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder} if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default } String name = content.getName(); if (name == null) { name = ""; } parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); for (FormBodyPart p : parts) { entity.addPart(p); } postOrPut.setEntity(entity); } else { //not using multipart postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8)); } return postOrPut; } // It is has one stream, it is the post body, put the params in the URL else { String fullQueryUrl = url + wparams.toQueryString(); HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { Long size = contentStream[0].getSize(); postOrPut.setEntity( new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { Long size = contentStream[0].getSize(); postOrPut.setEntity( new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } return postOrPut; } } throw new SolrServerException("Unsupported method: " + request.getMethod()); }
From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java
/** * /*from w ww. j a v a 2 s .c o m*/ * @date 2013-1-7 ?11:08:54 * @param toFetchURL * @return */ public FetchResult request(FetchRequest req) throws Exception { FetchResult fetchResult = new FetchResult(); HttpUriRequest request = null; HttpEntity entity = null; String toFetchURL = req.getUrl(); boolean isPost = false; try { if (Http.Method.GET.equalsIgnoreCase(req.getHttpMethod())) request = new HttpGet(toFetchURL); else if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())) { request = new HttpPost(toFetchURL); isPost = true; } else if (Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) request = new HttpPut(toFetchURL); else if (Http.Method.HEAD.equalsIgnoreCase(req.getHttpMethod())) request = new HttpHead(toFetchURL); else if (Http.Method.OPTIONS.equalsIgnoreCase(req.getHttpMethod())) request = new HttpOptions(toFetchURL); else if (Http.Method.DELETE.equalsIgnoreCase(req.getHttpMethod())) request = new HttpDelete(toFetchURL); else throw new Exception("Unknown http method name"); //???,?? // TODO ?delay? synchronized (mutex) { //?? long now = (new Date()).getTime(); //?Host?? if (now - lastFetchTime < config.getPolitenessDelay()) Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); //????HOST??URL lastFetchTime = (new Date()).getTime(); } //GZIP???GZIP? request.addHeader("Accept-Encoding", "gzip"); for (Iterator<Entry<String, String>> it = headers.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); request.addHeader(entry.getKey(), entry.getValue()); } //? Header[] headers = request.getAllHeaders(); for (Header h : headers) { Map<String, List<String>> hs = req.getHeaders(); String key = h.getName(); List<String> val = hs.get(key); if (val == null) val = new ArrayList<String>(); val.add(h.getValue()); hs.put(key, val); } req.getCookies().putAll(this.cookies); fetchResult.setReq(req); HttpEntity reqEntity = null; if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod()) || Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) { if (!req.getFiles().isEmpty()) { reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Iterator<Entry<String, List<File>>> it = req.getFiles().entrySet().iterator(); it .hasNext();) { Entry<String, List<File>> e = it.next(); String paramName = e.getKey(); for (File file : e.getValue()) { // For File parameters ((MultipartEntity) reqEntity).addPart(paramName, new FileBody(file)); } } for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it .hasNext();) { Entry<String, List<Object>> e = it.next(); String paramName = e.getKey(); for (Object paramValue : e.getValue()) { // For usual String parameters ((MultipartEntity) reqEntity).addPart(paramName, new StringBody( String.valueOf(paramValue), "text/plain", Charset.forName("UTF-8"))); } } } else { List<NameValuePair> params = new ArrayList<NameValuePair>(req.getParams().size()); for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it .hasNext();) { Entry<String, List<Object>> e = it.next(); String paramName = e.getKey(); for (Object paramValue : e.getValue()) { params.add(new BasicNameValuePair(paramName, String.valueOf(paramValue))); } } reqEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8); } if (isPost) ((HttpPost) request).setEntity(reqEntity); else ((HttpPut) request).setEntity(reqEntity); } //?? HttpResponse response = httpClient.execute(request); headers = response.getAllHeaders(); for (Header h : headers) { Map<String, List<String>> hs = fetchResult.getHeaders(); String key = h.getName(); List<String> val = hs.get(key); if (val == null) val = new ArrayList<String>(); val.add(h.getValue()); hs.put(key, val); } //URL fetchResult.setFetchedUrl(toFetchURL); String uri = request.getURI().toString(); if (!uri.equals(toFetchURL)) if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) fetchResult.setFetchedUrl(uri); entity = response.getEntity(); //??? int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { Header locationHeader = response.getFirstHeader("Location"); //301?302?URL?? if (locationHeader != null && (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) fetchResult.setMovedToUrl( URLCanonicalizer.getCanonicalURL(locationHeader.getValue(), toFetchURL)); } //???OKURLstatusCode?? //??? if (this.site.getSkipStatusCode() != null && this.site.getSkipStatusCode().trim().length() > 0) { String[] scs = this.site.getSkipStatusCode().split(","); for (String code : scs) { int c = CommonUtil.toInt(code); //????entity if (statusCode == c) { assemPage(fetchResult, entity); break; } } } fetchResult.setStatusCode(statusCode); return fetchResult; } //?? if (entity != null) { fetchResult.setStatusCode(statusCode); assemPage(fetchResult, entity); return fetchResult; } } catch (Throwable e) { fetchResult.setFetchedUrl(e.toString()); fetchResult.setStatusCode(Status.INTERNAL_SERVER_ERROR.ordinal()); return fetchResult; } finally { try { if (entity == null && request != null) request.abort(); } catch (Exception e) { throw e; } } fetchResult.setStatusCode(Status.UNSPECIFIED_ERROR.ordinal()); return fetchResult; }
From source file:com.starclub.enrique.BuyActivity.java
public void updateCredit(int credit) { progress = new ProgressDialog(this); progress.setCancelable(false);//from w ww . j a va 2s. co m progress.setMessage("Updating..."); progress.show(); m_nCredit = credit; new Thread() { public void run() { HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 30000); HttpConnectionParams.setSoTimeout(myParams, 30000); DefaultHttpClient hc = new DefaultHttpClient(myParams); ResponseHandler<String> res = new BasicResponseHandler(); String url = Utils.getUpdateUrl(); HttpPost postMethod = new HttpPost(url); String responseBody = ""; try { MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("cid", new StringBody("" + MyConstants.CID)); reqEntity.addPart("token", new StringBody("" + Utils.getUserToken())); reqEntity.addPart("user_id", new StringBody("" + Utils.getUserID())); reqEntity.addPart("credit", new StringBody("" + m_nCredit)); postMethod.setEntity(reqEntity); responseBody = hc.execute(postMethod, res); System.out.println("update result = " + responseBody); JSONObject result = new JSONObject(responseBody); if (result != null) { boolean status = result.optBoolean("status"); if (status) { m_handler.sendEmptyMessage(1); return; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { } m_handler.sendEmptyMessage(-1); } }.start(); }
From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java
/** * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing * this track to the public.//from ww w . j ava2s . com * * @param fileUri * @param contentType */ private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) { String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, ""); String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, ""); String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY, "trackable"); File gpxFile = new File(fileUri.getEncodedPath()); String hostname = getString(R.string.osm_post_host); Integer port = new Integer(getString(R.string.osm_post_port)); HttpHost targetHost = new HttpHost(hostname, port, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; String responseText = ""; int statusCode = 0; Cursor metaData = null; String sources = null; try { metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { sources = metaData.getString(0); } if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) { throw new IOException("Unable to upload track with materials derived from Google Maps."); } // The POST to the create node HttpPost method = new HttpPost(getString(R.string.osm_post_context)); // Preemptive basic auth on the first request method.addHeader( new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method)); // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(gpxFile)); entity.addPart("description", new StringBody(queryForTrackName())); entity.addPart("tags", new StringBody(queryForNotes())); entity.addPart("visibility", new StringBody(visibility)); method.setEntity(entity); // Execute the POST to OpenStreetMap response = httpclient.execute(targetHost, method); // Read the response statusCode = response.getStatusLine().getStatusCode(); InputStream stream = response.getEntity().getContent(); responseText = convertStreamToString(stream); } catch (IOException e) { Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e); responseText = getString(R.string.osm_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG); toast.show(); } catch (AuthenticationException e) { Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e); responseText = getString(R.string.osm_failed) + e.getLocalizedMessage(); Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG); toast.show(); } finally { if (metaData != null) { metaData.close(); } } if (statusCode == 200) { Log.i(TAG, responseText); CharSequence text = getString(R.string.osm_success) + responseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } else { Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText); CharSequence text = getString(R.string.osm_failed) + responseText; Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
public WebResponse multipartPostUrl(String sPage, boolean prefix, HashMap<String, ContentBody> nameValuePairs) throws UnsupportedEncodingException { WebResponse wr = null;//from ww w .j av a2 s. c o m String pageURL = (prefix ? this.urlBase + sPage : sPage); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Set<String> fields = nameValuePairs.keySet(); for (String fieldName : fields) { entity.addPart(fieldName, nameValuePairs.get(fieldName)); } return doMultiPartPost(pageURL, entity); }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
public WebResponse multipartPostUrl(String sPage, boolean prefix, List<BasicNameValuePair> nameValuePairs) throws UnsupportedEncodingException { WebResponse wr = null;/*from www . j av a 2 s . com*/ String pageURL = (prefix ? this.urlBase + sPage : sPage); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (BasicNameValuePair nv : nameValuePairs) { entity.addPart(nv.getName(), new StringBody(nv.getValue())); } return this.doMultiPartPost(pageURL, entity); /* HttpPost webPost = new HttpPost(pageURL); webPost.setEntity(entity); HttpResponse response = null ; try { response = client.execute(webPost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String sBody = responseHandler.handleResponse(response); wr = new WebResponse(response.getStatusLine().getStatusCode(), sBody); } catch (IOException ex) { log.error(ex.getMessage(), ex); } finally { if (response != null) { consumeContent( response.getEntity() ); } } return wr; */ }