List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:org.hyperic.hq.hqapi1.HQConnection.java
/** * Issue a POST against the API./*from w ww . ja v a 2 s . c om*/ * * @param path * The web service endpoint * @param params * A Map of key value pairs that are added to the post data * @param file * The file to post * @param responseHandler * The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response. * @return The response object from the operation. This response will be of * the type given in the responseHandler argument. * @throws IOException * If a network error occurs during the request. */ public <T> T doPost(String path, Map<String, String> params, File file, ResponseHandler<T> responseHandler) throws IOException { HttpPost post = new HttpPost(); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(file.getName(), new FileBody(file)); for (Map.Entry<String, String> paramEntry : params.entrySet()) { multipartEntity.addPart(new FormBodyPart(paramEntry.getKey(), new StringBody(paramEntry.getValue()))); } post.setEntity(multipartEntity); return runMethod(post, path, responseHandler); }
From source file:org.gitana.platform.client.support.RemoteImpl.java
@Override public void upload(String uri, InputStream in, long length, String mimetype, String filename) throws Exception { String URL = buildURL(uri, false); HttpPost httpPost = new HttpPost(URL); InputStreamBody inputStreamBody = new InputStreamBody(in, mimetype, filename); MultipartEntity entity = new MultipartEntity(); entity.addPart(filename, inputStreamBody); httpPost.setEntity(entity);// w w w . java 2 s .c o m HttpResponse httpResponse = invoker.execute(httpPost); if (!HttpUtil.isOk(httpResponse)) { throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity())); } // consume the response fully so that the client connection can be reused EntityUtils.consume(httpResponse.getEntity()); }
From source file:org.gitana.platform.client.support.RemoteImpl.java
@Override public void upload(String uri, byte[] bytes, String mimetype, String filename) throws Exception { String URL = buildURL(uri, false); HttpPost httpPost = new HttpPost(URL); HttpPayload payload = new HttpPayload(); payload.setBytes(bytes);/* w ww . j a v a2s. c o m*/ payload.setContentType(mimetype); payload.setFilename(filename); payload.setLength(bytes.length); MultipartEntity entity = new MultipartEntity(); entity.addPart(filename, new HttpPayloadContentBody(payload)); httpPost.setEntity(entity); HttpResponse httpResponse = invoker.execute(httpPost); if (!HttpUtil.isOk(httpResponse)) { throw new RuntimeException("Upload failed: " + EntityUtils.toString(httpResponse.getEntity())); } // consume the response fully so that the client connection can be reused EntityUtils.consume(httpResponse.getEntity()); }
From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java
public void execute() throws MojoExecutionException { this.getLog().info("Uploading project to BukkitDev"); final String gameVersion = this.getGameVersion(); final URIBuilder builder = new URIBuilder(); final MultipartEntity entity = new MultipartEntity(); HttpPost request;/*from w w w . j a v a 2 s .c om*/ // create the request builder.setScheme("http"); builder.setHost("dev.bukkit.org"); builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json"); try { entity.addPart("file_type", new StringBody(this.getFileType())); entity.addPart("name", new StringBody(this.project.getArtifact().getVersion())); entity.addPart("game_versions", new StringBody(gameVersion)); entity.addPart("change_log", new StringBody(this.changeLog)); entity.addPart("known_caveats", new StringBody(this.knownCaveats)); entity.addPart("change_markup_type", new StringBody(this.markupType)); entity.addPart("caveats_markup_type", new StringBody(this.markupType)); entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact()))); } catch (final UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage()); } // create the actual request try { request = new HttpPost(builder.build()); request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0"); request.setHeader("X-API-Key", this.key); request.setEntity(entity); } catch (final URISyntaxException exception) { throw new MojoExecutionException(exception.getMessage()); } this.getLog().debug(request.toString()); // send the request and handle any replies try { final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case 201: this.getLog().info("File uploaded successfully."); break; case 403: this.getLog().error( "You have not specifed your API key correctly or do not have permission to upload to that project."); break; case 404: this.getLog().error("Project was not found. Either it is specified wrong or been renamed."); break; case 422: this.getLog().error("There was an error in uploading the plugin"); this.getLog().debug(request.toString()); this.getLog().debug(EntityUtils.toString(response.getEntity())); break; default: this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode()); break; } } catch (final ClientProtocolException exception) { throw new MojoExecutionException(exception.getMessage()); } catch (final IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }
From source file:gov.medicaid.screening.dao.impl.BaseDAO.java
/** * Posts the Datagrid form.//from w ww .j av a2 s. c o m * * @param hostId * the unique host identifier * @param client * the client to use * @param httppost * the postback resource * @param postFragments * the fragments to include * @param multipartForm * to use multipart or regular form entity * @return the response entity * @throws ClientProtocolException * for protocol connection error * @throws IOException * for IO related errors * @throws ServiceException * if the post execution leads to an error */ protected HttpEntity postForm(String hostId, DefaultHttpClient client, HttpPost httppost, String[][] postFragments, boolean multipartForm) throws ClientProtocolException, IOException, ServiceException { HttpEntity entity = null; if (multipartForm) { MultipartEntity multiPartEntity = new MultipartEntity(); for (String[] params : postFragments) { multiPartEntity.addPart(params[0], new StringBody(params[1])); } entity = multiPartEntity; } else { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (String[] params : postFragments) { parameters.add(new BasicNameValuePair(params[0], params[1])); } entity = new UrlEncodedFormEntity(parameters); } httppost.setEntity(entity); HttpResponse postResponse = client.execute(httppost); verifyAndAuditCall(hostId, postResponse); return postResponse.getEntity(); }
From source file:org.hyperic.hq.hqapi1.HQConnection.java
/** * Issue a POST against the API./*from w w w. jav a 2 s. co m*/ * * @param path The web service endpoint * @param o The object to POST. This object will be serialized into XML * prior to being sent. * @param responseHandler * The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response. * @return The response object from the operation. This response will be of * the type given in the responseHandler argument. * @throws IOException If a network error occurs during the request. */ public <T> T doPost(String path, Object o, ResponseHandler<T> responseHandler) throws IOException { HttpPost post = new HttpPost(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { XmlUtil.serialize(o, bos, Boolean.FALSE); } catch (JAXBException e) { ServiceError error = new ServiceError(); error.setErrorCode("UnexpectedError"); error.setReasonText("Unable to serialize response"); if (_log.isDebugEnabled()) { _log.debug("Unable to serialize response", e); } return responseHandler.getErrorResponse(error); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("postdata", new StringBody(bos.toString("UTF-8"), Charset.forName("UTF-8"))); post.setEntity(multipartEntity); return runMethod(post, path, responseHandler); }
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException { HttpClient base = new DefaultHttpClient(); SSLContext ctx = null;/*from www .jav a 2 s. c om*/ try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException ex) { log("exception in sendFormPost():"); } X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; try { ctx.init(null, new TrustManager[] { tm }, null); } catch (KeyManagementException ex) { log("exception in sendFormPost():"); } SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); HttpClient client = new DefaultHttpClient(ccm, base.getParams()); try { HttpPost post = new HttpPost(url); MultipartEntity multipart = new MultipartEntity(); for (String key : additionalParams.keySet()) multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8"))); if (proj != null) { multipart.addPart("uploaded_file", new FileBody(proj)); } post.setEntity(multipart); HttpResponse resp = client.execute(post); HttpEntity out = resp.getEntity(); InputStream in = out.getContent(); return FileUtils.readStream(in); } catch (Exception ex) { throw new IOException("POST failed", ex); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception ex) { // ignore } } }
From source file:com.carapp.login.splashActivity.java
private void getClientBranch() { MultipartEntity entity = new MultipartEntity(); try {/* w ww.j a v a 2 s . c o m*/ entity.addPart("action", new StringBody("init_config")); new AsyncWebServiceProcessingTask(context, entity, messagecheck, new AsynckCallback() { @Override public void run(String result) { if (UIUtils.checkJson(result, context)) { try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.optString("satus").equals("success")) { PdfInfo.client = jsonObject.optString("client"); PdfInfo.branch = jsonObject.optString("branch"); Util.showCustomDialogWithoutButton(context, "Message", messagechecksucces, new Callback2() { @Override public void ok(final Dialog dialog) { final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { dialog.dismiss(); new AsyncWebServiceProcessingTask(context, null, "Please wait while checking date", new AsynckCallback() { @Override public void run(String result) { Log.e("date", "" + result); String sysdate = android.text.format.DateFormat .format("dd/MM/yyyy", new java.util.Date()) .toString(); if (result.equals(sysdate)) { Toast.makeText(context, "date match", Toast.LENGTH_SHORT).show(); new AsyncWebServiceProcessingTask( context, null, messagecheckday, new AsynckCallback() { @Override public void run( String result) { int day = Integer .parseInt( result); Calendar calendar = Calendar .getInstance(); int Today = calendar .get(Calendar.DAY_OF_WEEK); day++; if (day == Today) { Toast.makeText( context, "day is correct", Toast.LENGTH_SHORT) .show(); String ma_a = null; try { WifiManager wiman = (WifiManager) getSystemService( Context.WIFI_SERVICE); ma_a = wiman .getConnectionInfo() .getMacAddress(); Log.i(t, "" + ma_a); } catch (Exception e1) { e1.printStackTrace(); Log.i(t, " " + e1); } MultipartEntity entity = new MultipartEntity(); try { entity.addPart( "action", new StringBody( "device_authentication")); entity.addPart( "mac_address", new StringBody( ma_a)); new AsyncWebServiceProcessingTask( context, entity, "Checking License", new AsynckCallback() { @Override public void run( String result) { if (UIUtils .checkJson( result, context)) { try { JSONObject jsonObject = new JSONObject( result); if (jsonObject .optString( "satus") .equals("success")) { Toast.makeText( context, "LicenseCheck sucesses", Toast.LENGTH_SHORT) .show(); startActivity( new Intent( context, LoginActivity.class)); finish(); } else if (jsonObject .optString( "satus") .equals("error")) { Util.showCustomDialog( context, "Error", jsonObject .optString( "msg")); } } catch (Exception e) { e.printStackTrace(); } } } }).execute( PdfInfo.newjobcard); } catch (Exception e) { e.printStackTrace(); } } else { Util.showCustomDialogWithoutButton( context, "Error", messagecheckdayerror + " server day is " + day + " but your device is" + Today, new Callback2() { @Override public void ok( final Dialog dialog) { final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { dialog.dismiss(); finish(); } }; handler.postDelayed( runnable, 5000); } }); } } }).execute(PdfInfo.dayaddress); } else { Util.showCustomDialogWithoutButton( context, "Error", messagecheckdateerror + " server date is " + result + " but device date is " + sysdate, new Callback2() { @Override public void ok( final Dialog dialog) { new Timer().schedule( new TimerTask() { @Override public void run() { dialog.dismiss(); finish(); } }, 5000); } }); } } }).execute(PdfInfo.dateaddress); } }; handler.postDelayed(runnable, 5000); } }); } else if (jsonObject.optString("satus").equals("error")) { Util.showCustomDialogWithoutButton(context, "Message", messagechecksucces, new Callback2() { @Override public void ok(final Dialog dialog) { new Timer().schedule(new TimerTask() { @Override public void run() { dialog.dismiss(); finish(); } }, 5000); } }); } } catch (Exception e) { e.printStackTrace(); } } } }).execute(PdfInfo.newjobcard); } catch (Exception e) { e.printStackTrace(); } }
From source file:dk.kasperbaago.JSONHandler.JSONHandler.java
public String getURL() { //Making a HTTP client HttpClient client = new DefaultHttpClient(); //Declaring HTTP response HttpResponse response = null;//from www . j a v a 2s .co m String myReturn = null; try { //Making a HTTP getRequest or post request if (method == "get") { String parms = ""; if (this.parameters.size() > 0) { parms = "?"; parms += URLEncodedUtils.format(this.parameters, "utf-8"); } Log.i("parm", parms); Log.i("URL", this.url + parms); HttpGet getUrl = new HttpGet(this.url + parms); //Executing the request response = client.execute(getUrl); } else if (method == "post") { HttpPost getUrl = new HttpPost(this.url); //Sets parameters to add MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int i = 0; i < this.parameters.size(); i++) { if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) { entity.addPart(parameters.get(i).getName(), new FileBody(new File(parameters.get(i).getValue()))); } else { entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName())); } } getUrl.setEntity(entity); //Executing the request response = client.execute(getUrl); } else { return "false"; } //Returns the data HttpEntity content = response.getEntity(); InputStream mainContent = content.getContent(); myReturn = this.convertToString(mainContent); this.HTML = myReturn; Log.i("Result", myReturn); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return myReturn; }
From source file:edu.scripps.fl.pubchem.web.entrez.EUtilsWebSession.java
private MultipartEntity addParts(MultipartEntity entity, Collection<Object> pairs) throws UnsupportedEncodingException { Iterator<Object> iter = pairs.iterator(); while (iter.hasNext()) { String name = iter.next().toString(); String key = iter.hasNext() ? iter.next().toString() : ""; entity.addPart(name, new StringBody(key.toString())); }/*from w w w . j a va 2 s. c om*/ return entity; }