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.BungeniServiceAccess.java
public HashMap<String, ContentBody> attachmentEditSubmitPostQuery(HashMap<String, ContentBody> formFields, String title, String description, String fFileName) { try {//from w w w .j a v a2 s .co m formFields.put("form.title", new StringBody(title)); formFields.put("form.data.up_action", new StringBody("update")); formFields.put("form_data_file", new FileBody(new File(new URI(fFileName)), getMimeType(fFileName))); formFields.put("form.description", new StringBody(description)); formFields.put("form.language-empty-marker", new StringBody("1")); formFields.put("form.type-empty-marker", new StringBody("1")); return formFields; } catch (URISyntaxException ex) { log.error("Error getting URI to file ", ex); return formFields; } catch (UnsupportedEncodingException ex) { log.error("Encoding exception for field ", ex); return formFields; } }
From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java
public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException { HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl()); // nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple")); // for (int i = 0; i < parametres.length; i += 2) { // nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1])); // }// ww w .j av a 2s . c om // method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); // String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} // String substring = string.substring(string.indexOf("{"), // string.lastIndexOf("}") + 1); try { multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel())); multipartEntity.addPart("category", new StringBody(category.toString())); multipartEntity.addPart("name", new StringBody(title)); if (level != null) { multipartEntity.addPart("level", new StringBody(level.toString())); } } catch (UnsupportedEncodingException e) { throw new JiwigoException(e); } // StringBody contentBody = new StringBody(substring, // Charset.forName("UTF-8")); // multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("image", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } HttpResponse response; StringBuilder sb = new StringBuilder(); try { response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod); int responseStatusCode = response.getStatusLine().getStatusCode(); switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_FORBIDDEN: throw new JiwigoException("status code was : " + responseStatusCode); case HttpURLConnection.HTTP_NOT_FOUND: throw new JiwigoException("status code was : " + responseStatusCode); default: throw new JiwigoException("status code was : " + responseStatusCode); } HttpEntity resultEntity = response.getEntity(); BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity); BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { reader.close(); } } catch (ClientProtocolException e) { throw new JiwigoException(e); } catch (IOException e) { throw new JiwigoException(e); } String stringResult = sb.toString(); }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Upload a missing file to the lookaside cache. * /*from ww w. ja va 2 s . c o m*/ * Pre: upload file is missing as determined by * {@link UploadSourceCommand#checkSourceAvailable()}. * * @param subMonitor * @return The result of the upload. */ private UploadSourceResult upload(final IProgressMonitor subMonitor) throws UploadFailedException { HttpClient client = getClient(); try { String uploadUrl = projectRoot.getLookAsideCache().getUploadUrl().toString(); if (fedoraSslEnabled) { // user requested a Fedora SSL enabled client client = fedoraSslEnable(client); } else if (trustAllSSLEnabled) { // use an trust-all SSL enabled client client = trustAllSslEnable(client); } HttpPost post = new HttpPost(uploadUrl); FileBody uploadFileBody = new FileBody(fileToUpload); // For the actual upload we must not provide the // "filename" parameter (FILENAME_PARAM_NAME). Otherwise, // the file won't be stored in the lookaside cache. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILE_PARAM_NAME, uploadFileBody); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); // Not sure why it's ~ content-length * 2, but that's what it is... final long totalsize = reqEntity.getContentLength() * 2; subMonitor.beginTask(NLS.bind(FedoraPackagerText.UploadSourceCommand_uploadingFileSubTaskName, fileToUpload.getName()), 100 /* use percentage */); subMonitor.worked(0); // Custom listener for progress reporting of the file upload IRequestProgressListener progL = new IRequestProgressListener() { private int count = 0; private int worked = 0; private int updatedWorked = 0; @Override public void transferred(final long bytesWritten) { count++; worked = updatedWorked; if (subMonitor.isCanceled()) { throw new OperationCanceledException(); } // Since this listener may be called *a lot*, don't // do the calculation to often. if ((count % 1024) == 0) { updatedWorked = // multiply by 85 (instead of 100) since upload // progress cannot be 100% accurate. (int) ((double) bytesWritten / totalsize * 85); if (updatedWorked > worked) { worked = updatedWorked; subMonitor.worked(updatedWorked); } } } }; // We need to wrap the entity which we want to upload in our // custom entity, which allows for progress listening. CoutingRequestEntity countingEntity = new CoutingRequestEntity(reqEntity, progL); post.setEntity(countingEntity); // TODO: This may throw some certificate exception. We should // handle this case and throw a specific exception in order to // report this to the user. I.e. advise to use use $ fedora-cert -n HttpResponse response = client.execute(post); subMonitor.done(); return new UploadSourceResult(response); } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
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;// ww w.ja va 2 s .co m 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:MyZone.Settings.java
public boolean createNewUser(String username, String firstName, String lastName, String gender, String searchable) {//from w ww . j av a 2 s. c o m globalProperties = new globalAttributes(); try { if (!(new File(prefix + username).exists())) { boolean success = (new File(prefix + username)).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/audios").exists())) { boolean success = (new File(prefix + username + "/audios")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/videos").exists())) { boolean success = (new File(prefix + username + "/videos")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/photos").exists())) { boolean success = (new File(prefix + username + "/photos")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones").exists())) { boolean success = (new File(prefix + username + "/zones")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones/All").exists())) { boolean success = (new File(prefix + username + "/zones/All")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/zones/All/wall").exists())) { boolean success = (new File(prefix + username + "/zones/All/wall")).mkdirs(); if (!success) return false; } if (!(new File(prefix + "/CAs").exists())) { boolean success = (new File(prefix + "/CAs")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/cert").exists())) { boolean success = (new File(prefix + username + "/cert")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/friends").exists())) { boolean success = (new File(prefix + username + "/friends")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/keys").exists())) { boolean success = (new File(prefix + username + "/keys")).mkdirs(); if (!success) return false; } if (!(new File(prefix + username + "/thumbnails").exists())) { boolean success = (new File(prefix + username + "/thumbnails")).mkdirs(); if (!success) return false; } File file = new File(prefix + username + "/keys/" + username + ".pub"); boolean pubKeyExists = file.exists(); file = new File(prefix + username + "/keys/" + username + ".pri"); boolean priKeyExists = file.exists(); KeyPairUtil x = new KeyPairUtil(); KeyPair keys = null; if (!pubKeyExists || !priKeyExists) { keys = x.generateKeys(prefix + username + "/keys/", username, globalProperties.keyPairAlgorithm, globalProperties.certificateKeySize); } if (keys != null) keyFound = true; certFound = false; if (CAServerName != null) { File caKeyFile = new File(prefix + "/CAs/CA@" + CAServerName + ".pub"); CAKeyFound = true; if (!caKeyFile.exists()) { CAKeyFound = false; } } else { CAKeyFound = false; } certCorrupted = false; this.username = username; zones.clear(); friends.clear(); mirrors.clear(); originals.clear(); pendingFriendships.clear(); awaitingFriendships.clear(); sentMirroringRequests.clear(); receivedMirroringRequests.clear(); passphrases.clear(); zone z = new zone(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis(), Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis(), "All", 1800, null); zones.add(z); lastSyncTime1 = 0; lastSyncTime2 = 0; save(ALL); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://joinmyzone.com/upload.php"); FileBody publicKey = new FileBody(new File(prefix + username + "/keys/" + username + ".pub")); StringBody sFirstName = new StringBody(firstName); StringBody sLastName = new StringBody(lastName); StringBody sGender = new StringBody(gender); StringBody sSearchable = new StringBody(searchable); StringBody sEmail = new StringBody(username); StringBody sResend = new StringBody("false"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("firstName", sFirstName); reqEntity.addPart("lastName", sLastName); reqEntity.addPart("gender", sGender); reqEntity.addPart("searchable", sSearchable); reqEntity.addPart("email", sEmail); reqEntity.addPart("re-email", sEmail); reqEntity.addPart("resendCertificate", sResend); reqEntity.addPart("publicKey", publicKey); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } } return true; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }/*from w w w . ja va 2 s .c o m*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * * @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 Exception if something goes wrong. *///from w w w . ja v a 2 s . c om public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) { 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:com.k42b3.neodym.oauth.Oauth.java
@SuppressWarnings("unused") private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body) throws Exception { // build request HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 6000); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase request;//from ww w.j ava 2 s.com if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("text", new StringBody(body)); request = new HttpPost(url); ((HttpPost) request).setEntity(entity); } else { throw new Exception("Invalid request method"); } // header Set<String> keys = header.keySet(); for (String key : keys) { request.setHeader(key, header.get(key)); } // execute HTTP Get Request logger.info("Request: " + request.getRequestLine()); HttpResponse httpResponse = httpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); String responseContent = EntityUtils.toString(entity); // log traffic if (trafficListener != null) { TrafficItem trafficItem = new TrafficItem(); trafficItem.setRequest(request); trafficItem.setResponse(httpResponse); trafficItem.setResponseContent(responseContent); trafficListener.handleRequest(trafficItem); } // check status code int statusCode = httpResponse.getStatusLine().getStatusCode(); if (!(statusCode >= 200 && statusCode < 300)) { JOptionPane.showMessageDialog(null, responseContent); throw new Exception("No successful status code"); } return entity; }
From source file:fm.smart.r1.activity.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String id) { String http_response = ""; int status_code = 0; HttpClient client = null;// w ww .j a va2 s .com String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds"); String auth = Main.username(this) + ":" + Main.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }
From source file:fm.smart.r1.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String item_id, String id, String to_record) { String http_response = ""; int status_code = 0; HttpClient client = null;/* w w w . j a v a 2s. com*/ String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds.json"); String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); StringBody version_part = new StringBody("2"); StringBody text_part = new StringBody(to_record); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); reqEntity.addPart("text", text_part); reqEntity.addPart("v", version_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }