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:nl.gridline.zieook.workflow.rest.CollectionImportCompleteTest.java
@Ignore private HttpResponse executePOST(String url, String data) { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPut post = new HttpPut(url); post.setHeader("Accept", "application/json"); try {// ww w. ja v a2 s .co m post.setEntity(new StringEntity(data)); return httpclient.execute(post); } catch (ClientProtocolException e) { LOG.error("upload failed", e); fail("upload failed"); } catch (IOException e) { LOG.error("upload failed", e); fail("upload failed"); } return null; }
From source file:org.cm.podd.report.util.RequestDataUtil.java
public static ResponseObject registerDeviceId(String deviceId, String token) { JSONObject jsonObj = null;// www.j av a 2 s.c o m int statusCode = 0; //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0); String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL); String reqUrl = serverUrl + "/gcm/"; Log.i(TAG, "submit url=" + reqUrl); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient client = new DefaultHttpClient(params); try { HttpPost post = new HttpPost(reqUrl); post.setHeader("Content-Type", "application/json"); if (token != null) { post.setHeader("Authorization", "Token " + token); } JSONObject data = new JSONObject(); try { data.put("gcmRegId", deviceId); } catch (JSONException e) { Log.e(TAG, "Error while create json object", e); } post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8)); HttpResponse response; response = client.execute(post); HttpEntity entity = response.getEntity(); // Detect server complaints statusCode = response.getStatusLine().getStatusCode(); Log.v(TAG, "status code=" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { InputStream in = entity.getContent(); String resp = FileUtil.convertInputStreamToString(in); Log.d(TAG, "Register device id : Response text= " + resp); jsonObj = new JSONObject(); entity.consumeContent(); } } catch (ClientProtocolException e) { Log.e(TAG, "error post data", e); } catch (IOException e) { Log.e(TAG, "Can't connect server", e); } finally { client.getConnectionManager().shutdown(); } return new ResponseObject(statusCode, jsonObj); }
From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java
protected DefaultHttpClient getHTTPClient() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override//from ww w .ja v a 2s . c o m public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 8181, sf); PlainSocketFactory plain = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", 8080, plain); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); DefaultHttpClient httpClient = new DefaultHttpClient(cm, params); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); return httpClient; }
From source file:com.yahala.ui.LoginActivitySmsView.java
public void sendSmsRequest() { Utilities.globalQueue.postRunnable(new Runnable() { @Override//from w w w. j av a2s .c o m public void run() { try { HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8); httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); SchemeRegistry registry = new SchemeRegistry(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry); HttpClient httpClient = new DefaultHttpClient(manager, httpParams); // HttpGet httpget = new HttpGet("/nhttps://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"+ phoneHash); HttpGet httpget = new HttpGet( "https://rest.nexmo.com/sms/json?api_key=***********&api_secret=***********=NEXMO&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); if (!Utils.IsInDebugMode()) { HttpResponse response = httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { FileLog.e("yahala", "Sms sent" + response.getEntity().getContent()); } else { FileLog.e("/nyahala", "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); } } else { Toast.makeText(getContext(), phoneHash, Toast.LENGTH_LONG); FileLog.e("/nyahala", "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash); } } catch (Exception e) { FileLog.e("yahala", e); } } }); }
From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java
/** * Starts uploading data./* w ww .j ava 2 s. c o m*/ */ private void startUploading() { if (uploadThread != null) { writeToLog("Upload thread active"); return; } uploadThread = new Thread(new Runnable() { @Override public void run() { uploadThreadRunning = true; while (uploadThreadRunning) { //get API key retrieveApiKey(); //get a list of non uploaded measurements MeasurementsDBIterator dbIterator = mDatabase.getNonUploadedMeasurements(); boolean success = true; String errorMsg = ""; int max = 0; int count = 0; // stop uploading if the upload is working only when the wifi is active if (wifiOnly && !NetUtils.isWifiConnected(getApplicationContext())) { writeToLog("WiFi only and WiFi is not connected."); try { Thread.sleep(newDataCheckInterval); } catch (Exception e) { } continue; } try { writeToLog("Checking if there are records for upload..."); if (dbIterator.getCount() > 0) { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0); writeToLog("MeasurementsUploaderService startUploading() - openCellUrl=" + openCellUrl); httppost = new HttpPost(openCellUrl); max = dbIterator.getCount(); count = 0; NumberFormat latLonFormat = NumberFormat.getNumberInstance(Locale.US); latLonFormat.setMaximumFractionDigits(10); while (dbIterator.hasNext() && uploadThreadRunning) { //upload measurements as a batch file count = uploadMeasurementsBatch(dbIterator, latLonFormat, count, max); Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION); progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max); progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count); sendBroadcast(progress); } // set all measurements as uploaded if (uploadThreadRunning) { mDatabase.setAllMeasurementsUploaded(); } // start uploading networks data if (uploadThreadRunning) { uploadNetworks(); } writeToLog("Uploaded " + count + " of " + max + " records."); httpclient.getConnectionManager().shutdown(); success = true; } else { writeToLog("No records for upload right now."); } } catch (Exception e) { writeExceptionToLog(e); success = false; errorMsg = e.getMessage(); } finally { dbIterator.close(); } Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION); progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max); progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count); progress.putExtra(OpenCellIDUploadService.XTRA_DONE, true); progress.putExtra(OpenCellIDUploadService.XTRA_SUCCESS, success); if (!success) { progress.putExtra(OpenCellIDUploadService.XTRA_FAILURE_MSG, errorMsg); } sendBroadcast(progress); try { Thread.sleep(newDataCheckInterval); } catch (Exception e) { } } } }); uploadThread.start(); }
From source file:ninja.utils.NinjaTestBrowser.java
public String postXml(String url, Object object) { try {//w w w . j av a 2 s. c o m httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(new XmlMapper().writeValueAsString(object), "utf-8"); entity.setContentType("application/xml; charset=utf-8"); post.setEntity(entity); post.releaseConnection(); // Here we go! return EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java
public static JSONObject CallFunction(String url, String[] paramNames, String[] paramVals, Context context) { JSONObject json = new JSONObject(); SchemeRegistry supportedSchemes = new SchemeRegistry(); SSLSocketFactory sf = getSocketFactory(DEBUG); // TODO we make assumptions about ports. supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", sf, 443)); HttpParams http_params = new BasicHttpParams(); ClientConnectionManager ccm = new ThreadSafeClientConnManager(http_params, supportedSchemes); // HttpParams http_params = httpclient.getParams(); http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpConnectionParams.setConnectionTimeout(http_params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, http_params); if (paramNames == null) { paramNames = new String[0]; }/*from w w w. jav a2 s. c om*/ if (paramVals == null) { paramVals = new String[0]; } if (paramNames.length != paramVals.length) { Log.w(TAG, "Incompatible number of param names and values, bailing on upload!"); return null; } SortedMap<String, String> sig_params = new TreeMap<String, String>(); HttpResponse response = null; HttpPost httppost = null; Log.d(TAG, "HTTP POST URL: " + url); try { httppost = new HttpPost(url); } catch (IllegalArgumentException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return json; } try { File file = null; // If this is a POST call, then it is a file upload. Check to see if // a // filename is given, and if so, open that file. // Get the title of the photo being uploaded so we can pass it into // the // MultipartEntityMonitored class to be broadcast for progress // updates. String title = ""; for (int i = 0; i < paramNames.length; ++i) { if (paramNames[i].equals("title")) { title = paramVals[i]; } else if (paramNames[i].equals("filename")) { file = new File(paramVals[i]); continue; } sig_params.put(paramNames[i], paramVals[i]); } MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(context, title); if (file != null) { mp_entity.addPart("userfile", new FileBody(file)); } for (Map.Entry<String, String> entry : sig_params.entrySet()) { mp_entity.addPart(entry.getKey(), new StringBody(entry.getValue())); } httppost.setEntity(mp_entity); response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String content = convertStreamToString(resEntity.getContent()); if (response.getStatusLine().getStatusCode() == 200) { try { json = new JSONObject(content.toString()); } catch (JSONException e1) { Log.w(TAG, "Response 200 received but invalid JSON."); json.put("fail", e1.getMessage()); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } else { Log.w(TAG, "File upload failed with response code:" + response.getStatusLine().getStatusCode()); json.put("fail", response.getStatusLine().getReasonPhrase()); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } else { Log.w(TAG, "Response does not contain a valid HTTP entity."); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (IllegalStateException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (IllegalArgumentException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (JSONException e) { } httpclient.getConnectionManager().shutdown(); return json; }
From source file:nl.gridline.zieook.workflow.rest.CollectionImportCompleteTest.java
@Ignore private int collectionUpload(String url, File file) { // upload binary collection data HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpEntity entity = new FileEntity(file, "binary/octet-stream"); HttpPut post = new HttpPut(url); post.setEntity(entity);// w ww .ja va 2 s . c om try { HttpResponse response = httpclient.execute(post); return response.getStatusLine().getStatusCode(); } catch (ClientProtocolException e) { LOG.error("upload failed", e); fail("upload failed"); } catch (IOException e) { LOG.error("upload failed", e); fail("upload failed"); } return 500; }
From source file:org.ancoron.osgi.test.glassfish.GlassfishDerbyTest.java
@Test(dependsOnGroups = { "glassfish-osgi-startup" }) public void testWebAvailability() throws NoSuchAlgorithmException, KeyManagementException, IOException { logTest();/*from w w w. j av a 2 s . c om*/ DefaultHttpClient http = getHTTPClient(); try { HttpGet httpget = new HttpGet("http://[::1]/movie/dummy/"); httpget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only httpget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); HttpResponse res = http.execute(httpget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access to secured page at '" + httpget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "]"); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); HttpGet httpsget = new HttpGet("https://[::1]/movie/dummy/"); httpsget.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Use HTTP 1.1 for this request only httpsget.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access to secured page at '" + httpsget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181), new UsernamePasswordCredentials("fail", "fail")); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() == 200) { fail("Gained access with invalid user role to secured page at '" + httpsget.getURI().toASCIIString() + "' [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); http.getCredentialsProvider().setCredentials(new AuthScope("[::1]", 8181), new UsernamePasswordCredentials("test", "test")); res = http.execute(httpsget); if (res.getStatusLine().getStatusCode() != 200) { fail("Failed to access " + httpsget.getURI().toASCIIString() + ": [status=" + res.getStatusLine().getStatusCode() + "] " + res.getStatusLine().getReasonPhrase()); } log.log(Level.INFO, "[HTTP] Got response for ''{0}'' [status={1}]", new Object[] { httpget.getURI().toASCIIString(), res.getStatusLine().getStatusCode() }); } finally { http.getConnectionManager().shutdown(); } }