List of usage examples for org.apache.http.params CoreProtocolPNames PROTOCOL_VERSION
String PROTOCOL_VERSION
To view the source code for org.apache.http.params CoreProtocolPNames PROTOCOL_VERSION.
Click Source Link
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. j av a 2 s. com 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.gsbabil.antitaintdroid.UtilityFunctions.java
public String httpFileUpload(String filePath) { String sResponse = ""; HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(MyApp.HTTP_OCR_URL); MultipartEntity mpEntity = new MultipartEntity(); File file = new File(filePath); ContentBody cbFile = new FileBody(file, "image/png"); mpEntity.addPart("image", cbFile); httppost.setEntity(mpEntity);//from w w w. j a v a2s. c om HttpResponse response = null; try { response = httpClient.execute(httppost); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { if (sResponse != null) { sResponse = sResponse.trim() + "\n" + line.trim(); } else { sResponse = line; } } Log.i(MyApp.TAG, sResponse); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } httpClient.getConnectionManager().shutdown(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return sResponse.trim(); }
From source file:net.vivekiyer.GAL.ActiveSyncManager.java
/** * @return the HttpClient object/*from w w w . j av a 2 s .com*/ * * Creates a HttpClient object that is used to POST messages to the Exchange server */ private HttpClient createHttpClient() { HttpParams httpParams = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); // Default connection and socket timeout of 120 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(httpParams, 120 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 120 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 131072); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", mAcceptAllCerts ? new FakeSocketFactory() : SSLSocketFactory.getSocketFactory(), 443)); HttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); // Set the headers httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android"); // Make sure we are not validating any hostnames SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return httpclient; }
From source file:ca.mcgill.hs.serv.LogFileUploaderService.java
/** * Uploads the specified file to the server. * /*from w ww. jav a 2s . co m*/ * @param fileName * The file to upload * @return A code indicating the result of the upload. */ private int uploadFile(final String fileName) { Log.d(TAG, "Uploading " + fileName); httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); httppost = new HttpPost(UPLOAD_URL); final File file = new File(HSAndroid.getStorageDirectory(), fileName); if (!file.exists()) { // File may be deleted while in the queue for uploading Log.d(TAG, "Unable to upload " + fileName + ". File does not exist."); return UPLOAD_FAILED_FILE_NOT_FOUND_ERROR_CODE; } Log.d(TAG, "MAC ADDRESS: " + wifiInfo.getMacAddress()); httppost.addHeader("MAC", wifiInfo.getMacAddress()); final MultipartEntity mpEntity = new MultipartEntity(); final ContentBody cbFile = new FileBody(file, "binary/octet-stream"); mpEntity.addPart("uploadedfile", cbFile); httppost.setEntity(mpEntity); try { final HttpResponse response = httpclient.execute(httppost); final HttpEntity resEntity = response.getEntity(); String responseMsg = ""; if (resEntity != null) { responseMsg = EntityUtils.toString(resEntity); resEntity.consumeContent(); } Log.i(TAG, "Server Response: " + responseMsg); if (responseMsg.contains("FAILURE")) { CURRENT_ERROR_CODE = UPLOAD_FAILED_ERROR_CODE; return UPLOAD_FAILED_ERROR_CODE; } // Move files to uploaded folder if successful else { Log.i(TAG, "Moving file to uploaded directory."); final File dest = new File(HSAndroid.getStorageDirectory(), HSAndroid.getAppString(R.string.uploaded_file_path)); if (!dest.isDirectory()) { if (!dest.mkdirs()) { throw new IOException("ERROR: Unable to create directory " + dest.getName()); } } if (!file.renameTo(new File(dest, file.getName()))) { throw new IOException("ERROR: Unable to transfer file " + file.getName()); } } } catch (final MalformedURLException e) { Log.e(TAG, android.util.Log.getStackTraceString(e)); CURRENT_ERROR_CODE = MALFORMEDURLEXCEPTION_ERROR_CODE; return MALFORMEDURLEXCEPTION_ERROR_CODE; } catch (final UnknownHostException e) { Log.e(TAG, android.util.Log.getStackTraceString(e)); CURRENT_ERROR_CODE = UNKNOWNHOSTEXCEPTION_ERROR_CODE; return UNKNOWNHOSTEXCEPTION_ERROR_CODE; } catch (final IOException e) { Log.e(TAG, android.util.Log.getStackTraceString(e)); CURRENT_ERROR_CODE = IOEXCEPTION_ERROR_CODE; return IOEXCEPTION_ERROR_CODE; } catch (final IllegalStateException e) { Log.e(TAG, android.util.Log.getStackTraceString(e)); CURRENT_ERROR_CODE = ILLEGALSTATEEXCEPTION_ERROR_CODE; return ILLEGALSTATEEXCEPTION_ERROR_CODE; } return NO_ERROR_CODE; }
From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java
public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId, boolean withGps) { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient httpClient = new DefaultHttpClient(params); try {//from w w w. ja v a 2 s .c o m HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/"); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("app_id", new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8"))); multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8"))); // ? ? multipartEntity.addPart("parent_id", new StringBody(Integer.toString(parentId), Charset.forName("UTF-8"))); multipartEntity.addPart("reply_id", new StringBody(Integer.toString(replyId), Charset.forName("UTF-8"))); if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) { multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8"))); } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) { multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8"))); } else { multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8"))); } multipartEntity.addPart("account_id", new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_name", new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_avatar", new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8"))); if (withGps) { if (Statics.currentLocation != null) { multipartEntity.addPart("latitude", new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8"))); multipartEntity.addPart("longitude", new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8"))); } } multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8"))); if (!TextUtils.isEmpty(imagePath)) { multipartEntity.addPart("images", new FileBody(new File(imagePath))); } httpPost.setEntity(multipartEntity); String resp = httpClient.execute(httpPost, new BasicResponseHandler()); return JSONParser.parseMessagesString(resp).get(0); } catch (Exception e) { return null; } }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToVideoBin(final Activity activity, final Handler handler, final String video_absolutepath, final String title, final String description, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doPOSTtoVideoBin starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. boolean failed = false; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); URI url = null;//from www .j a v a 2 s.co m try { url = new URI(res.getString(R.string.http_videobin_org_add)); } catch (URISyntaxException e) { // Ours is a fixed URL, so not likely to get here. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); e.printStackTrace(); return; } HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(video_absolutepath); entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file)); try { entity.addPart(res.getString(R.string.video_bin_API_api), new StringBody("1", "text/plain", Charset.forName("UTF-8"))); // title entity.addPart(res.getString(R.string.video_bin_API_title), new StringBody(title, "text/plain", Charset.forName("UTF-8"))); // description entity.addPart(res.getString(R.string.video_bin_API_description), new StringBody(description, "text/plain", Charset.forName("UTF-8"))); } catch (IllegalCharsetNameException e) { // error e.printStackTrace(); failed = true; } catch (UnsupportedCharsetException e) { // error e.printStackTrace(); return; } catch (UnsupportedEncodingException e) { // error e.printStackTrace(); failed = true; } post.setEntity(entity); // Here we go! String response = null; try { response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); } catch (ParseException e) { // error e.printStackTrace(); failed = true; } catch (ClientProtocolException e) { // error e.printStackTrace(); failed = true; } catch (IOException e) { // error e.printStackTrace(); failed = true; } client.getConnectionManager().shutdown(); // CHECK RESPONSE FOR SUCCESS!! if (!failed && response != null && response.matches(res.getString(R.string.video_bin_API_good_re))) { // We got back HTTP response with valid URL Log.d(TAG, " video bin got back URL " + response); } else { Log.d(TAG, " video bin got eror back:\n" + response); failed = true; } if (failed) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_failed_)); } }, 0); return; } // XXX Convert to preference for auto-email on videobin post // XXX ADD EMAIL NOTIF to all other upload methods // stuck on YES here, if email is defined. if (emailAddress != null && response != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, res.getString(R.string.http_videobin_org_add), response, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:com.lurencun.cfuture09.androidkit.http.Http.java
/** * /* w w w .j a va2 s . c o m*/ * * @param url * ?URL * @param entity * * @return ? * @throws ClientProtocolException * @throws IOException */ private static String doUpload(String url, SimpleMultipartEntity entity) throws ClientProtocolException, IOException { HttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); HttpResponse response; response = httpclient.execute(httppost); return EntityUtils.toString(response.getEntity()); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } }
From source file:com.sangupta.jerry.http.WebRequest.java
/** * Set the request HTTP Protocol version//from ww w . j a va 2 s .co m * * @param version * {@link HttpVersion} to use * * @return this very {@link WebRequest} */ public WebRequest version(final HttpVersion version) { return config(CoreProtocolPNames.PROTOCOL_VERSION, version); }
From source file:fr.eolya.utils.http.HttpLoader.java
public static Map<String, String> getAuthCookies(int authMode, String authLogin, String authPasswd, String authParam, String proxyHost, String proxyPort, String proxyExclude, String proxyUser, String proxyPassword) {//from ww w . j a va 2 s .c o m if (authMode == 0) return null; Map<String, String> authCookies = null; String[] aAuthParam = authParam.split("\\|"); // http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html DefaultHttpClient httpClient = new DefaultHttpClient(); // Proxy setProxy(httpClient, aAuthParam[0], proxyHost, proxyPort, proxyExclude, proxyUser, proxyPassword); HttpPost httpPost = new HttpPost(aAuthParam[0]); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); for (int i = 1; i < aAuthParam.length; i++) { String[] aPair = aAuthParam[i].split("="); aPair[1] = aPair[1].replaceAll("\\$\\$auth_login\\$\\$", authLogin); aPair[1] = aPair[1].replaceAll("\\$\\$auth_passwd\\$\\$", authPasswd); nameValuePairs.add(new BasicNameValuePair(aPair[0], aPair[1])); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setHeader("ContentType", "application/x-www-form-urlencoded"); HttpResponse response = httpClient.execute(httpPost, localContext); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } List<Cookie> cookies = httpClient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { authCookies = new HashMap<String, String>(); for (Cookie c : cookies) { // TODO: What about the path, the domain ??? authCookies.put(c.getName(), c.getValue()); } } httpPost.abort(); } catch (ClientProtocolException e) { return null; } catch (IOException e) { return null; } return authCookies; }