/** * register to the server * * @param context Activity or Service context * @param regId gcmId registered from Google */ public static boolean register(Context context, String regId) { String serverUrl = ServerUrl.SERVER_URL_GCM_REGISTER(); String uid = PreferenceControl.getUID(); try { DefaultHttpClient httpClient = HttpSecureClientGenerator.getSecureHttpClient(); HttpPost httpPost = new HttpPost(serverUrl); httpClient .getParams() .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("uid", uid); builder.addTextBody("regId", regId); httpPost.setEntity(builder.build()); boolean result = uploader(httpClient, httpPost); GCMRegistrar.setRegisteredOnServer(context, result); return result; } catch (Exception e) { GCMRegistrar.setRegisteredOnServer(context, false); return false; } }
protected HttpPost setupPostWithFileName(HttpPost request, String fileName) { if (fileName == null || fileName.length() == 0) return request; ContentBody fileBody = new FileBody(new File(fileName), ContentType.DEFAULT_BINARY); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .setBoundary("boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49"); multipartEntity.addPart("file", fileBody); request.setEntity(multipartEntity.build()); // MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, // "boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49", Charset.forName("UTF-8")); // mpEntity.addPart("userfile", fileBody); // request.setEntity(mpEntity); // FileEntity entity = new FileEntity(new File(fileName), // ContentType.APPLICATION_OCTET_STREAM); // BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE,"application/json"); // request.getParams().setBooleanParameter("http.protocol.expect-continue", false); // entity.setContentType(basicHeader); // request.setEntity(mpEntity); return request; }
/*.................................................................................................................*/ public void prepareBuilder(MultipartEntityBuilder builder, String cipresTool, String jobID) { if (builder != null) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("tool", cipresTool); if (StringUtil.notEmpty(jobID)) builder.addTextBody("metadata.clientJobId", jobID); builder.addTextBody("metadata.statusEmail", "true"); builder.addTextBody("vparam.runtime_", "0.50", ContentType.TEXT_PLAIN); } }
@Override protected String doInBackground(String... url) { String resp = ""; String username = ""; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLSEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLSEC); HttpPost request = new HttpPost(url[0]); MultipartEntityBuilder MEB = MultipartEntityBuilder.create(); Charset chars = Charset.forName("UTF-8"); MEB.setCharset(chars); MEB.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); try { JSONArray contactsArray = new JSONArray(); for (int i = 0; i < selectedItemList.size(); i++) { JSONObject contactObj = new JSONObject(); File getFile = new File(context.getFilesDir().getPath() + "/", selectedItemList.get(i)); FileBody fb = new FileBody(getFile); contactObj.put("contact", selectedItemList.get(i)); contactsArray.put(contactObj); MEB.addPart(selectedItemList.get(i), fb); fb = null; } selectedItemList.clear(); byte[] contacts = contactsArray.toString().getBytes(); MEB.addBinaryBody("contactsArray", contacts); contactsArray = null; HttpEntity ent = MEB.build(); request.setEntity(ent); // request.setEntity(new ByteArrayEntity(file.toString().getBytes("UTF8"))); MyHttpClient Client = LogonClass.Client; Client.putContext(context); HttpResponse response = Client.execute(request); contactsArray = null; resp = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); resp = "none is righteous"; } Log.e(TAG, "response is " + resp); return resp; }
private static String uploadToSever(String url, List<NameValuePair> nameValuePairs) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < nameValuePairs.size(); index++) { if (nameValuePairs.get(index).getName().equalsIgnoreCase("filename")) { builder.addPart( nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()))); } else { builder.addPart( nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); HttpEntity responseEntity = response.getEntity(); String strResponse = ""; if (responseEntity != null) { strResponse = EntityUtils.toString(responseEntity); } return strResponse; } catch (IOException e) { throw e; } finally { httpPost = null; httpClient = null; } }
public ImageData recognize(byte[] jpeg) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("imgFile", jpeg, ContentType.DEFAULT_BINARY, "cam.jpg"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(uri); post.addHeader("Authorization", credentials.createAuthorizationHeaderValue()); post.setEntity(builder.build()); try { HttpResponse response = httpclient.execute(post); VisualRecognitionResponse r = objectMapper.readValue( EntityUtils.toString(response.getEntity()), VisualRecognitionResponse.class); return r.getImages().get(0); } catch (IOException e) { throw new RuntimeException(e); } }
private void upload(File file) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(getUploadUrl()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fb = new FileBody(file); builder.addPart("log_file", fb); HttpEntity entity = builder.build(); post.setEntity(entity); try { HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); Log.d( ApeicUtil.TAG_HTTP, "Status code of uploading " + file.getName() + ": " + String.valueOf(statusCode)); if (statusCode == 200) { file.delete(); } } catch (IOException e) { Log.e(ApeicUtil.TAG_HTTP, e.getMessage()); } }
@Override protected Integer doInBackground(Trick... trick) { try { int level = trick[0].getLevel(); String videoPath = trick[0].getVideoFilePath(); String rollPath = trick[0].getDataRollFilePath(); String pitchPath = trick[0].getDataPitchFilePath(); String yawPath = trick[0].getDataYawFilePath(); String altitudePath = trick[0].getDataAltitudeFilePath(); HttpClient client = new DefaultHttpClient(); File videoFile = new File(videoPath); File rollFile = new File(rollPath); File pitchFile = new File(pitchPath); File yawFile = new File(yawPath); File altitudeFile = new File(altitudePath); HttpPost post = new HttpPost("http://skate.3du.es"); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addTextBody("user", "demoUser"); entityBuilder.addTextBody("level", String.valueOf(level)); entityBuilder.addBinaryBody("video", videoFile); entityBuilder.addBinaryBody("roll", rollFile); entityBuilder.addBinaryBody("pitch", pitchFile); entityBuilder.addBinaryBody("yaw", yawFile); entityBuilder.addBinaryBody("altitude", altitudeFile); // add more key/value pairs here as needed HttpEntity entity = entityBuilder.build(); post.setEntity(entity); HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object. * * @param httpRequest * @param request * @throws AuthFailureError */ private static void setMultiPartBody( HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { // Return if Request is not MultiPartRequest if (!(request instanceof MultiPartRequest)) { return; } // MultipartEntity multipartEntity = new // MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); /* example for setting a HttpMultipartMode */ builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Iterate the fileUploads Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads(); for (Map.Entry<String, File> entry : fileUpload.entrySet()) { builder.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue())); } ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8); // Iterate the stringUploads Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads(); for (Map.Entry<String, String> entry : stringUpload.entrySet()) { try { builder.addPart( ((String) entry.getKey()), new StringBody((String) entry.getValue(), contentType)); } catch (Exception e) { e.printStackTrace(); } } httpRequest.setEntity(builder.build()); }
private String uploadMedia( String mediaType, String mediaFilename, String mediaText, String mediaCaption) { // Log.d("uploadMedia()", "param name: " + params.get(index).getName()); /* String baseUrl = BuildConfig.BASE_URL + "/upload_media.json"; double latLng[] = YellrUtils.getLocation(getApplicationContext()); String lat = String.valueOf(latLng[0]); String lng = String.valueOf(latLng[1]); String languageCode = Locale.getDefault().getLanguage(); String url = baseUrl + "?cuid=" + YellrUtils.getCUID(getApplicationContext()) //cuid + "&language_code=" + languageCode + "&lat=" + lat + "&lng=" + lng; */ String uploadMediaJson = "{}"; String baseUrl = BuildConfig.BASE_URL + "/upload_media.json"; String url = YellrUtils.buildUrl(getApplicationContext(), baseUrl); if (url != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); // params.add(new BasicNameValuePair("cuid", cuid)); params.add(new BasicNameValuePair("media_type", mediaType)); // params.add(new BasicNameValuePair("media_type", mediaType)); if (!mediaFilename.equals("")) { params.add(new BasicNameValuePair("media_file", mediaFilename)); } if (!mediaText.equals("")) { params.add(new BasicNameValuePair("media_text", mediaText)); } if (!mediaCaption.equals("")) { params.add(new BasicNameValuePair("caption", mediaCaption)); } // // derived from // http://stackoverflow.com/a/2937140 // HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { if (params.get(index).getName().equalsIgnoreCase("media_file") && !mediaType.equalsIgnoreCase("text")) { // we only need to add a file if our media object type is not text // if (mediaType != "text") { // If the key equals to "media_file", we use FileBody to transfer the data Log.d("uploadMedia()", "adding binary file: " + params.get(index).getValue()); entityBuilder.addPart( params.get(index).getName(), new FileBody(new File(params.get(index).getValue()))); // } } else { Log.d("uploadMedia()", "adding text field: " + params.get(index).getValue()); // Normal string data entityBuilder.addPart( params.get(index).getName(), new StringBody(params.get(index).getValue(), ContentType.TEXT_PLAIN)); } } try { HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); InputStream content = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); // StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } uploadMediaJson = builder.toString(); Log.d("PublishPostIntentService.uploadMedia()", "JSON: " + uploadMediaJson); } catch (Exception e) { // Toast.makeText(this, "upload_media: " + e.toString(), Toast.LENGTH_SHORT).show(); Log.d("PublishPostIntentService.uploadMedia()", "ERROR: " + e.toString()); // e.printStackTrace(); } } return uploadMediaJson; }
private String publishPost( int assignmentId, // String languageCode, // String title, // double lat, // double lng, String mediaId) { // String mediaObjects){ /* String baseUrl = BuildConfig.BASE_URL + "/publish_post.json"; // get the location, but if the user has turned off location services, // it will come back null. If it's null, just dump out. // TODO: pop-up a dialog maybe?? double latLng[] = YellrUtils.getLocation(getApplicationContext()); if (latLng == null ) return null; String lat = String.valueOf(latLng[0]); String lng = String.valueOf(latLng[1]); String languageCode = Locale.getDefault().getLanguage(); String url = baseUrl + "?cuid=" + YellrUtils.getCUID(getApplicationContext()) //cuid + "&language_code=" + languageCode + "&lat=" + lat + "&lng=" + lng; */ String publishPostJson = "{}"; String baseUrl = BuildConfig.BASE_URL + "/publish_post.json"; String url = YellrUtils.buildUrl(getApplicationContext(), baseUrl); if (url != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); // params.add(new BasicNameValuePair("cuid", cuid)); params.add(new BasicNameValuePair("assignment_id", String.valueOf(assignmentId))); // params.add(new BasicNameValuePair("language_code", languageCode)); // params.add(new BasicNameValuePair("title", title)); // params.add(new BasicNameValuePair("lat", String.valueOf(lat))); // params.add(new BasicNameValuePair("lng", String.valueOf(lng))); params.add(new BasicNameValuePair("media_objects", "[\"" + mediaId + "\"]")); // // derived from // http://stackoverflow.com/a/2937140 // HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); try { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < params.size(); index++) { entityBuilder.addPart( params.get(index).getName(), new StringBody(params.get(index).getValue(), ContentType.TEXT_PLAIN)); } HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, localContext); final String toastMsg; if (response.getStatusLine().getStatusCode() == 200) { toastMsg = "Post Successful!"; } else { toastMsg = "Problem Submitting Post."; } handler.post( new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_SHORT).show(); } }); // InputStream content = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); // StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } publishPostJson = builder.toString(); Log.d("PublishPostIntentService.publishPost()", "JSON: " + publishPostJson); } catch (IOException e) { e.printStackTrace(); } } else { Log.d("PublishPostIntentService.publishPost()", "URL was null!!!"); } return publishPostJson; }