List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
/** * Login to Bungeni via the OAuth route/*www . j a va 2 s. co m*/ * @param oauthForwardURL * @param oauthCameFromURL * @return * @throws UnsupportedEncodingException * @throws IOException */ private String oauthAuthenticate(String oauthForwardURL, String oauthCameFromURL) throws UnsupportedEncodingException, IOException { final HttpPost post = new HttpPost(oauthForwardURL); final HashMap<String, ContentBody> nameValuePairs = new HashMap<String, ContentBody>(); nameValuePairs.put("login", new StringBody(this.getUser())); nameValuePairs.put("password", new StringBody(this.getPassword())); nameValuePairs.put("camefrom", new StringBody(oauthCameFromURL)); nameValuePairs.put("actions.login", new StringBody("login")); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Set<String> fields = nameValuePairs.keySet(); for (String fieldName : fields) { entity.addPart(fieldName, nameValuePairs.get(fieldName)); } HttpContext context = new BasicHttpContext(); post.setEntity(entity); HttpResponse oauthResponse = client.execute(post, context); // if the OAuth page retrieval failed throw an exception if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(oauthResponse.getStatusLine().toString()); } String currentUrl = getRequestEndContextURL(context); // consume the response ResponseHandler<String> responseHandler = new BasicResponseHandler(); String sBody = responseHandler.handleResponse(oauthResponse); consumeContent(oauthResponse.getEntity()); return currentUrl; }
From source file:com.omt.syncpad.DemoKitActivity.java
private static void postFile() { try {//from w w w .j a v a 2 s. c om File f = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + fileName); mf.writeToFile(f); Log.i(TAG, "Midi file generated. Posting file"); HttpPost httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); entity.addPart("filename", new StringBody(fileName)); entity.addPart("fileext", new StringBody(extName)); entity.addPart("upfile", new FileBody(f)); HttpClient httpclient = new DefaultHttpClient(); httppost.setEntity(entity); httpclient.execute(httppost); //HttpResponse response = httpclient.execute(httppost); //Do something with response... Log.i(TAG, "File posted"); } catch (Exception e) { // show error e.printStackTrace(); return; } }
From source file:setiquest.renderer.Utils.java
/** * Send a random BSON file./*from ww w . j av a2s .c o m*/ * @return the response from the web server. */ public static String sendRandomBsonFile() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(getOfflineSubjectsURL()); String filename = getRandomFile(getBsonDataDir()); File f = new File(filename); if (!f.exists()) { Log.log("sendRandonBsonFile(): File \"" + filename + "\" does not exists."); return "sendRandonBsonFile(): File \"" + filename + "\" does not exists."; } //Parse info from the name. //Old file = act1207.1.5.bson = actId, pol, subchannel //New file name: act1207.1.0.5.bson = actid, pol, obsType, subchannel int actId = 0; int obsId = 0; int pol = 0; String subchannel = "0"; String shortName = f.getName(); String[] parts = shortName.split("\\."); if (parts.length == 4) //Old name type { actId = Integer.parseInt(parts[0].substring(3)); obsId = 0; //Default to this. pol = Integer.parseInt(parts[1]); subchannel = parts[2]; } else if (parts.length == 5) //New name type { actId = Integer.parseInt(parts[0].substring(3)); pol = Integer.parseInt(parts[1]); obsId = Integer.parseInt(parts[2]); subchannel = parts[3]; } else { Log.log("sendRandonBsonFile(): bad bson file name: " + shortName); return "sendRandonBsonFile(): bad bson file name: " + shortName; } Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); //Log.log(response.toString()); String sendResult = "Sending: " + shortName + "\n"; sendResult += "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; return sendResult; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "undefined"; }
From source file:net.zypr.api.Protocol.java
public JSONObject doStreamPost(APIVerbs apiVerb, Hashtable<String, String> urlParameters, Hashtable<String, String> postParameters, InputStream inputStream) throws APICommunicationException, APIProtocolException { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().addActiveRequestCount(); long t1 = System.currentTimeMillis(); JSONObject jsonObject = null;/*w w w. jav a2 s. co m*/ JSONParser jsonParser = new JSONParser(); try { DefaultHttpClient httpclient = getHTTPClient(); HttpPost httpPost = new HttpPost(buildURL(apiVerb, urlParameters)); HttpProtocolParams.setUseExpectContinue(httpPost.getParams(), false); MultipartEntity multipartEntity = new MultipartEntity(); if (postParameters != null) for (Enumeration enumeration = postParameters.keys(); enumeration.hasMoreElements();) { String key = enumeration.nextElement().toString(); String value = postParameters.get(key); multipartEntity.addPart(key, new StringBody(value)); Debug.print("HTTP POST : " + key + "=" + value); } if (inputStream != null) { InputStreamBody inputStreamBody = new InputStreamBody(inputStream, "binary/octet-stream"); multipartEntity.addPart("audio", inputStreamBody); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpclient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 200) throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode() + " - " + httpResponse.getStatusLine().getReasonPhrase()); HttpEntity httpEntity = httpResponse.getEntity(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent())); jsonObject = (JSONObject) jsonParser.parse(bufferedReader); bufferedReader.close(); httpclient.getConnectionManager().shutdown(); } catch (ParseException parseException) { throw new APIProtocolException(parseException); } catch (IOException ioException) { throw new APICommunicationException(ioException); } catch (ClassCastException classCastException) { throw new APIProtocolException(classCastException); } finally { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().removeActiveRequestCount(); long t2 = System.currentTimeMillis(); Debug.print(buildURL(apiVerb, urlParameters) + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + jsonObject); } return (jsonObject); }
From source file:com.pc.dailymile.DailyMileClient.java
public Long addNoteWithImage(String note, File imageFile) throws Exception { HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL); HttpResponse response = null;/* ww w . j a va2 s .c om*/ try { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg")); mpEntity.addPart("media[type]", new StringBody("image")); mpEntity.addPart("message", new StringBody(note)); mpEntity.addPart("[share_on_services][facebook]", new StringBody("false")); mpEntity.addPart("[share_on_services][twitter]", new StringBody("false")); mpEntity.addPart("oauth_token", new StringBody(oauthToken)); request.setEntity(mpEntity); // send the request response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new RuntimeException( "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note); } if (statusCode == 201) { Header loc = response.getFirstHeader("Location"); if (loc != null) { String locS = loc.getValue(); if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) { try { return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1)); } catch (NumberFormatException e) { return null; } } } } return null; } finally { try { if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } //EntityUtils.consume(response.getEntity()); } catch (IOException e) { // ignore } } }
From source file:com.francisli.processing.http.HttpClient.java
/** * @param files HashMap: a collection of files to send to the server *//*from w w w .j ava 2 s .c o m*/ public HttpRequest POST(String path, Map params, Map files) { //// clean up path a little bit- remove whitespace, add slash prefix path = path.trim(); if (!path.startsWith("/")) { path = "/" + path; } //// finally, invoke request HttpPost post = new HttpPost(getHost().toURI() + path); MultipartEntity multipart = null; //// if files passed, set up a multipart request if (files != null) { multipart = new MultipartEntity(); post.setEntity(multipart); for (Object key : files.keySet()) { Object value = files.get(key); if (value instanceof byte[]) { multipart.addPart((String) key, new ByteArrayBody((byte[]) value, "bytes.dat")); } else if (value instanceof String) { File file = new File((String) value); if (!file.exists()) { file = parent.sketchFile((String) value); } multipart.addPart((String) key, new FileBody(file)); } } } //// if params passed, format into a query string and append if (params != null) { if (multipart == null) { ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); for (Object key : params.keySet()) { Object value = params.get(key); pairs.add(new BasicNameValuePair(key.toString(), value.toString())); } String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8); if (path.contains("?")) { path = path + "&" + queryString; } else { path = path + "?" + queryString; } try { post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); } catch (UnsupportedEncodingException ex) { System.err.println("HttpClient: Unable to set POST data from parameters"); } } else { for (Object key : params.keySet()) { Object value = params.get(key); try { multipart.addPart((String) key, new StringBody((String) value)); } catch (UnsupportedEncodingException ex) { System.err.println("HttpClient: Unable to add " + key + ", " + value); } } } } if (useOAuth) { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret); consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret); try { consumer.sign(post); } catch (Exception e) { System.err.println("HttpClient: Unable to sign POST request for OAuth"); } } HttpRequest request = new HttpRequest(this, getHost(), post); request.start(); return request; }
From source file:org.rapidandroid.activity.FormReviewer.java
private void uploadFile(final String filename) { Toast.makeText(getApplicationContext(), FILE_UPLOAD_BEGUN, Toast.LENGTH_LONG).show(); Thread t = new Thread() { @Override/*from w w w .j a v a2 s. com*/ public void run() { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(filename); HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; // Post, check and show the result (not really spectacular, // but works): response = httpclient.execute(httpost); Log.d("httpPost", "Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } success = true; } catch (Exception ex) { Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); success = false; } finally { mDebugHandler.post(mFinishUpload); } } }; t.start(); }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * // ww w. java 2 s .c o m * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws UnsupportedEncodingException * @throws IOException * @throws ClientProtocolException */ public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws UnsupportedEncodingException, IOException, ClientProtocolException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java
public static ProjectLocation uploadProject(SPServerInfo serviceInfo, String name, File project, UserPrompterFactory session, CookieStore cookieStore) throws URISyntaxException, ClientProtocolException, IOException, JSONException { HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore); try {//from www . ja v a 2 s .c om MultipartEntity entity = new MultipartEntity(); ContentBody fileBody = new FileBody(project); ContentBody nameBody = new StringBody(name); entity.addPart("file", fileBody); entity.addPart("name", nameBody); HttpPost request = new HttpPost(ClientSideSessionUtils.getServerURI(serviceInfo, "/" + ClientSideSessionUtils.REST_TAG + "/jcr", "name=" + name)); request.setEntity(entity); JSONMessage message = httpClient.execute(request, new JSONResponseHandler()); JSONObject response = new JSONObject(message.getBody()); return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo); } catch (AccessDeniedException e) { session.createUserPrompter("You do not have sufficient privileges to create a new workspace.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); return null; } finally { httpClient.getConnectionManager().shutdown(); } }