List of usage examples for org.apache.http.entity.mime HttpMultipartMode STRICT
HttpMultipartMode STRICT
To view the source code for org.apache.http.entity.mime HttpMultipartMode STRICT.
Click Source Link
From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java
/** * Upload a file to the given URL//from w ww .j av a 2 s . c om * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); }
From source file:net.kidlogger.kidlogger.KLService.java
protected void sendPOST(File f, String content, String mimeType, boolean delFile, boolean increaseUploadedSize) { Date now = new Date(); String fileDate = String.format("%td/%tm/%tY %tT", now, now, now, now); String devField = Settings.getDeviceField(this); if (devField.equals("undefined") || devField.equals("")) { return;/* w w w . java 2s . c om*/ } if (f == null) { //app.logError(CN + "sendPOST", "f parameter is null"); return; } if (mimeType == null) { //app.logError(CN + "sendPOST", "mime parameter is null"); return; } try { //HttpParams params = new BasicHttpParams(); //HttpConnectionParams.setSoTimeout(params, 40000); //HttpConnectionParams.setConnectionTimeout(params, 40000); //HttpClient client = new DefaultHttpClient(params); HttpClient client = new DefaultHttpClient(); String postUrl = getString(R.string.upload_link); //String postUrl = "http://10.0.2.2/denwer/"; HttpPost post = new HttpPost(postUrl); FileBody bin = new FileBody(f, mimeType, f.getName()); StringBody sb1 = new StringBody(devField); //dYZ-PC-Gzq StringBody sb2 = new StringBody(content); StringBody sb3 = new StringBody("Android " + Build.VERSION.RELEASE); StringBody sb4 = new StringBody(Settings.getApiVersion(this)); StringBody sb5 = new StringBody(fileDate); StringBody sb6 = new StringBody("append"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT); reqEntity.addPart("file", bin); reqEntity.addPart("device", sb1); reqEntity.addPart("content", sb2); reqEntity.addPart("client-ver", sb3); reqEntity.addPart("app-ver", sb4); reqEntity.addPart("client-date-time", sb5); reqEntity.addPart("file-store", sb6); post.setEntity(reqEntity); // Check Internet connection //if(isInternetOn()){ if (!mNoConnectivity) { HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { pStatus = EntityUtils.toString(resEntity); if (pStatus.equalsIgnoreCase("Ok")) { if (mimeType.equals("text/html")) saveToPref("filePointer", filePointer); FILE_SENT = f.getName(); SIZE_SENT = f.length(); postSentOk = true; app.mSendTime = new String(fileDate); if (increaseUploadedSize) uploadedSize = uploadedSize + (int) f.length(); } else { // Check response of server if (pStatus.contains("<html>")) return; else if (pStatus.contains(new String(REJECT))) stopUploadMedia = true; else if (pStatus.contains(new String(UPDATE)) || pStatus.contains(new String(BAD_DEV)) || pStatus.contains(new String(NOT_FOUND))) unregisterReceiver(timeTick); //app.logError(CN + "sendPOST", pStatus + " file: " + f.getName()); } app.logError(CN + "sendPOST", "Response: " + pStatus + " file: " + f.getName() + " size: " + f.length()); //Log.i(CN + "sendPOST", "Response: " + pStatus); } else app.logError(CN + "sendPOST", "Response is NULL"); } //else // app.logError(CN + "sendPOST", "No any Internet connections"); if (delFile) { f.delete(); } } catch (Exception e) { if (delFile) { f.delete(); } app.logError(CN + "sendPOST", e.toString() + " file:" + f.getName() + " size: " + f.length()); } }
From source file:com.lexmark.saperion.services.PutFileToSaperionECM.java
private static HttpEntity buildMultipart(String base64FileString, String fileName) throws IOException { String indexString = "indexName"; StringBuilder jsonString = new StringBuilder(); jsonString.append(setECMRequest(indexString, fileName)); StringBody jsonBody = new StringBody(jsonString.toString(), ContentType.TEXT_PLAIN); FormBodyPart jsonBodyPart = new FormBodyPart("body", jsonBody); jsonBodyPart.addField("Content-Type", "application/json; charset=UTF-8"); jsonBodyPart.addField("Content-ID", "body"); StringBuilder fileBuilder = new StringBuilder(); fileBuilder.append(base64FileString); StringBody fileBody = new StringBody(fileBuilder.toString(), ContentType.TEXT_PLAIN); FormBodyPart fileBodyPart = new FormBodyPart("filePart", fileBody); fileBodyPart.addField("Content-Type", "image/png"); fileBodyPart.addField("Content-ID", "<imagefile>"); MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create(); multipartBuilder.setMode(HttpMultipartMode.STRICT); multipartBuilder.setBoundary("2676ff6efebdb664f8f7ccb34f864e25"); multipartBuilder.addPart(jsonBodyPart); multipartBuilder.addPart(fileBodyPart); /*ByteArrayOutputStream out = new ByteArrayOutputStream(); multipartBuilder.build().writeTo(out); out.close();/*from ww w. j a va 2 s . c o m*/ String s = out.toString("UTF-8"); System.err.println("output IS "+s);*/ HttpEntity entity = multipartBuilder.build(); return entity; }
From source file:com.basistech.rosette.api.RosetteAPI.java
private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter, HttpPost post) {/*from w w w . jav a 2 s .c o m*/ MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMimeSubtype("mixed"); builder.setMode(HttpMultipartMode.STRICT); FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request", // Make sure we're not mislead by someone who puts a charset into the mime type. new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) { @Override public String getFilename() { return null; } @Override public void writeTo(OutputStream out) throws IOException { finalWriter.writeValue(out, request); } @Override public String getTransferEncoding() { return MIME.ENC_BINARY; } @Override public long getContentLength() { return -1; } }); // Either one of 'name=' or 'Content-ID' would be enough. partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\""); partBuilder.setField("Content-ID", "request"); builder.addPart(partBuilder.build()); partBuilder = FormBodyPartBuilder.create("content", new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType()))); partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\""); partBuilder.setField("Content-ID", "content"); builder.addPart(partBuilder.build()); builder.setCharset(StandardCharsets.UTF_8); HttpEntity entity = builder.build(); post.setEntity(entity); }
From source file:org.apache.solr.client.solrj.impl.HttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;//from w ww . j a v a 2 s. c om InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } 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); } int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + ClientUtils.toQueryString(wparams, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; // only send this list of params as query string params ModifiableSolrParams queryParams = new ModifiableSolrParams(); for (String param : this.queryParams) { String[] value = wparams.getParams(param); if (value != null) { for (String v : value) { queryParams.add(param, v); } wparams.remove(param); } } LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url + ClientUtils.toQueryString(queryParams, false)); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); 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, Charset.forName("UTF-8")))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } 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); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(wparams, false); HttpPost post = new HttpPost(url + pstr); // 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) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // XXX client already has this set, is this needed? method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null; boolean shouldClose = true; boolean success = false; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); Header ctHeader = response.getLastHeader("content-type"); String contentType; if (ctHeader != null) { contentType = ctHeader.getValue(); } else { contentType = ""; } // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: if (processor == null) { throw new RemoteSolrException(httpStatus, "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null); } } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; success = true; return rsp; } String procCt = processor.getContentType(); if (procCt != null) { String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT); String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT); if (!procMimeType.equals(mimeType)) { // unexpected mime type String msg = "Expected mime type " + procMimeType + " but got " + mimeType + "."; Header encodingHeader = response.getEntity().getContentEncoding(); String encoding; if (encodingHeader != null) { encoding = encodingHeader.getValue(); } else { encoding = "UTF-8"; // try UTF-8 } try { msg = msg + " " + IOUtils.toString(respBody, encoding); } catch (IOException e) { throw new RemoteSolrException(httpStatus, "Could not parse response with encoding " + encoding, e); } RemoteSolrException e = new RemoteSolrException(httpStatus, msg, null); throw e; } } // if(true) { // ByteArrayOutputStream copy = new ByteArrayOutputStream(); // IOUtils.copy(respBody, copy); // String val = new String(copy.toByteArray()); // System.out.println(">RESPONSE>"+val+"<"+val.length()); // respBody = new ByteArrayInputStream(copy.toByteArray()); // } NamedList<Object> rsp = null; String charset = EntityUtils.getContentCharSet(response.getEntity()); try { rsp = processor.processResponse(respBody, charset); } catch (Exception e) { throw new RemoteSolrException(httpStatus, e.getMessage(), e); } if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = java.net.URLDecoder.decode(msg.toString(), UTF_8); } throw new RemoteSolrException(httpStatus, reason, null); } success = true; return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (Throwable t) { } // ignore if (!success) { method.abort(); } } } }