List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:cl.mmoscoso.geocomm.sync.GeoCommLogInAsyncTask.java
@Override protected Boolean doInBackground(Void... params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); try {/* w ww. j a va 2 s . c o m*/ // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("username", this.name)); nameValuePairs.add(new BasicNameValuePair("password", this.pass)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); //int responseCode = 201; switch (responseCode) { case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, point; try { //Log.i(TAGNAME, "tamao: "+ responseBody); jObj = new JSONObject(responseBody); this.value_login = jObj.getInt("status"); this.id_user = jObj.getInt("id"); //Log.i(TAGNAME, "Value: "+ this.value_login ); //this.name_user = jObj.getString("name"); //this.id_user = jObj.getInt("id"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; default: Log.i(TAGNAME, "Error"); //Toast.makeText(this.context,"ERROR!!", Toast.LENGTH_SHORT).show(); break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return true; }
From source file:com.lazerycode.selenium.filedownloader.FileDownloader.java
/** * Perform the file/image download.//from www .j a v a 2 s . c o m * * @param element * @param attribute * @return * @throws IOException * @throws NullPointerException */ private String downloader(WebElement element, String attribute, String Filename) throws IOException, NullPointerException, URISyntaxException { String fileToDownloadLocation = element.getAttribute(attribute); if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!"); URL fileToDownload = new URL(fileToDownloadLocation); //changed by Raul File downloadedFile = new File(Filename); //+ " fileToDownload.getFile().replaceFirst("/|\\\\", "").replace("?", "")); if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true); HttpClient client = new DefaultHttpClient(); BasicHttpContext localContext = new BasicHttpContext(); //LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState); if (this.mimicWebDriverCookieState) { localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies())); } HttpGet httpget = new HttpGet(fileToDownload.toURI()); HttpParams httpRequestParameters = httpget.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects); httpget.setParams(httpRequestParameters); // LOG.info("Sending GET request for: " + httpget.getURI()); HttpResponse response = client.execute(httpget, localContext); this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode(); //LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt); //LOG.info("Downloading file: " + downloadedFile.getName()); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile); response.getEntity().getContent().close(); String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath(); // LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'"); return downloadedFileAbsolutePath; }
From source file:cl.mmoscoso.geocomm.sync.GeoCommGetRoutesOwnerAsyncTask.java
@Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); HttpPost httppost = new HttpPost(this.hostname); Log.i(TAGNAME, "Try to connect to " + this.hostname); try {// w ww .j a v a 2 s .c o m List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(this.id_user))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.i(TAGNAME, "Post Request"); HttpResponse response = httpclient.execute(httppost); int responseCode = response.getStatusLine().getStatusCode(); switch (responseCode) { default: Toast.makeText(this.context, R.string.error_not200code, Toast.LENGTH_SHORT).show(); break; case 200: HttpEntity entity = response.getEntity(); if (entity != null) { String responseBody = EntityUtils.toString(entity); //Log.i(TAGNAME, responseBody); JSONObject jObj, ruta; try { Log.i(TAGNAME, "Reading JSONResponse"); jObj = new JSONObject(responseBody); SharedPreferences preferences = this.context.getSharedPreferences("userInformation", context.MODE_PRIVATE); Boolean is_allroutes = preferences.getBoolean("is_allroutes", false); for (int i = 0; i < jObj.length(); i++) { ruta = new JSONObject(jObj.getString(jObj.names().getString(i))); if (is_allroutes) { if (ruta.getBoolean("public") == false) { list_routes.add(new GeoCommRoute(ruta.getString("name"), ruta.getString("owner"), ruta.getInt("id"), ruta.getInt("totalPoints"), ruta.getString("description"), ruta.getBoolean("public"))); } } else list_routes.add(new GeoCommRoute(ruta.getString("name"), ruta.getString("owner"), ruta.getInt("id"), ruta.getInt("totalPoints"), ruta.getString("description"), ruta.getBoolean("public"))); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } catch (IOException e) { // TODO Auto-generated catch block Log.e(TAGNAME, e.toString()); return false; } return true; }
From source file:com.ovea.facebook.client.DefaultFacebookClient.java
private HttpClient httpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); DefaultHttpClient client = new DefaultHttpClient(params); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, sslSocketFactory)); return client; }
From source file:org.apache.olingo.fit.CXFOAuth2HttpClientFactory.java
@Override protected void init() throws OAuth2Exception { final URI authURI = OAuthClientUtils.getAuthorizationURI(oauth2GrantServiceURI.toASCIIString(), OAuth2Provider.CLIENT_ID, OAuth2Provider.REDIRECT_URI, null, null); // Disable automatic redirects handling final HttpParams params = new BasicHttpParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, false); final DefaultHttpClient httpClient = new DefaultHttpClient(params); JsonNode oAuthAuthorizationData = null; String authenticityCookie = null; try {// w ww . j ava2 s .com // 1. Need to (basic) authenticate against the OAuth2 service final HttpGet method = new HttpGet(authURI); method.addHeader("Authorization", "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes())); final HttpResponse response = httpClient.execute(method); // 2. Pull out OAuth2 authorization data and "authenticity" cookie (CXF specific) oAuthAuthorizationData = new XmlMapper().readTree(EntityUtils.toString(response.getEntity())); final Header setCookieHeader = response.getFirstHeader("Set-Cookie"); if (setCookieHeader == null) { throw new IllegalStateException("OAuth flow is broken"); } authenticityCookie = setCookieHeader.getValue(); } catch (Exception e) { throw new OAuth2Exception(e); } String code = null; try { // 3. Submit the HTTP form for allowing access to the application final URI location = new URIBuilder(oAuthAuthorizationData.get("replyTo").asText()) .addParameter("session_authenticity_token", oAuthAuthorizationData.get("authenticityToken").asText()) .addParameter("client_id", oAuthAuthorizationData.get("clientId").asText()) .addParameter("redirect_uri", oAuthAuthorizationData.get("redirectUri").asText()) .addParameter("oauthDecision", "allow").build(); final HttpGet method = new HttpGet(location); method.addHeader("Authorization", "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes())); method.addHeader("Cookie", authenticityCookie); final HttpResponse response = httpClient.execute(method); final Header locationHeader = response.getFirstHeader("Location"); if (response.getStatusLine().getStatusCode() != 303 || locationHeader == null) { throw new IllegalStateException("OAuth flow is broken"); } // 4. Get the authorization code value out of this last redirect code = StringUtils.substringAfterLast(locationHeader.getValue(), "="); EntityUtils.consumeQuietly(response.getEntity()); } catch (Exception e) { throw new OAuth2Exception(e); } // 5. Obtain the access token try { accessToken = OAuthClientUtils.getAccessToken(getAccessTokenService(), OAUTH2_CONSUMER, new AuthorizationCodeGrant(code)); } catch (OAuthServiceException e) { throw new OAuth2Exception(e); } if (accessToken == null) { throw new OAuth2Exception("No OAuth2 access token"); } }
From source file:com.restqueue.framework.client.messageproducers.BasicMessageSender.java
/** * This enables you to send a message./*from w w w .j a v a2 s . c o m*/ * * You must set either the stringBody (if you already have a json or xml message formatted) or the objectBody first before sending a message. * These can be set using setStringBodyAndType(String stringBody, MediaType asType) and setObjectBody(Object objectBody) respectively. * * You also must set the channel endpoint as well as the server IP address and port (if they vary from the defaults localhost and 9998). * * @return The result of the update giving you access to the http response code and error information */ public CreationResult sendMessage() { Object messageBody = null; if (stringBody == null && objectBody == null) { throw new IllegalArgumentException("String body and Object body cannot both be null."); } else { if (stringBody != null) { messageBody = stringBody; } if (objectBody != null) { messageBody = objectBody; } } if (channelEndpoint == null) { throw new IllegalArgumentException("The Channel Endpoint must be set."); } if (messageBody instanceof String && asType == null) { throw new IllegalArgumentException("The type must be set when using a String body."); } final String fullUrl = URLUtils.renderFullUrlFromIpAddressAndPort(serverIpAddress, serverPort, channelEndpoint); final HttpPost httpPost = new HttpPost(fullUrl + "/entries"); if (messageBody instanceof String) { httpPost.setEntity(createStringEntity((String) messageBody)); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, asType.toString()); } else { httpPost.setEntity( createStringEntity(new Serializer().toType(messageBody, MediaType.APPLICATION_JSON))); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); } for (Map.Entry<CustomHeaders, List<String>> entry : headerMap.entrySet()) { for (String headerValue : entry.getValue()) { httpPost.addHeader(entry.getKey().getName(), headerValue); } } final HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); final DefaultHttpClient client = new DefaultHttpClient(params); final HttpResponse response; try { response = client.execute(httpPost); } catch (HttpHostConnectException e) { throw new ChannelClientException( "Exception connecting to server at ip address:" + serverIpAddress + ", port:" + serverPort + ". Ensure server is running and configured using the right ip address and port.", e, ChannelClientException.ExceptionType.CONNECTION); } catch (ClientProtocolException e) { throw new ChannelClientException("Exception communicating with server at ip address:" + serverIpAddress + ", port:" + serverPort + ".", e, ChannelClientException.ExceptionType.TRANSPORT_PROTOCOL); } catch (Exception e) { throw new ChannelClientException("Unknown exception occurred when trying to send the message:", e, ChannelClientException.ExceptionType.UNKNOWN); } return new ResultsFactory().creationResultFromHttpPostResponse(response); }
From source file:com.nextgis.uikobserver.HttpSendData.java
@Override protected Void doInBackground(String... urls) { if (IsNetworkAvailible(mContext)) { String sPostBody = urls[0]; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://gis-lab.info:8090/"); HttpParams params = httppost.getParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE); HttpContext localContext = new BasicHttpContext(); try {//from ww w . j a v a2 s .co m StringEntity se = new StringEntity(sPostBody, "UTF8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); httppost.setHeader("Content-type", "application/json"); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost, localContext); Bundle bundle = new Bundle(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { bundle.putBoolean("error", false); } else { bundle.putBoolean("error", true); } bundle.putInt("src", mnType); Message msg = new Message(); msg.setData(bundle); if (mEventReceiver != null) { mEventReceiver.sendMessage(msg); } } catch (ClientProtocolException e) { mError = e.getMessage(); cancel(true); } catch (IOException e) { mError = e.getMessage(); cancel(true); } } else { Bundle bundle = new Bundle(); bundle.putBoolean("error", true); bundle.putString("err_msq", mContext.getString(R.string.sNetworkUnreach)); bundle.putInt("src", mnType); Message msg = new Message(); msg.setData(bundle); if (mEventReceiver != null) { mEventReceiver.sendMessage(msg); } } return null; }
From source file:io.vertigo.struts2.FileDownloader4Tests.java
/** * Perform the file/image download./*from w ww . j a va 2s . co m*/ * * @param element * @param attribute * @return downloadedFileAbsolutePath * @throws IOException * @throws NullPointerException */ private String downloader(final WebElement element, final String attribute) throws IOException, NullPointerException, URISyntaxException { final String fileToDownloadLocation = element.getAttribute(attribute); if (fileToDownloadLocation.trim().equals("")) { throw new NullPointerException("The element you have specified does not link to anything!"); } final URL fileToDownload = new URL(fileToDownloadLocation); final File downloadedFile = new TempFile(localDownloadPath, "test"); if (downloadedFile.canWrite() == false) { downloadedFile.setWritable(true); } try (final CloseableHttpClient client = HttpClientBuilder.create().build()) { final BasicHttpContext localContext = new BasicHttpContext(); LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState); if (mimicWebDriverCookieState) { localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies())); } final HttpGet httpget = new HttpGet(fileToDownload.toURI()); final HttpParams httpRequestParameters = httpget.getParams(); httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects); httpget.setParams(httpRequestParameters); LOG.info("Sending GET request for: " + httpget.getURI()); try (final CloseableHttpResponse response = client.execute(httpget, localContext)) { httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode(); LOG.info("HTTP GET request status: " + httpStatusOfLastDownloadAttempt); LOG.info("Downloading file: " + downloadedFile.getName()); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile); //response.getEntity().getContent().close(); } } final String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath(); LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'"); return downloadedFileAbsolutePath; }
From source file:org.sociotech.communitymashup.source.mendeley.sdkadaption.AdaptedDocumentServiceImpl.java
protected String callGetForRedirectUrl(String apiUrl) { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); try {//from w ww . j a va 2 s .c o m HttpGet httpget = new HttpGet(apiUrl); if (!requestParameters.isEmpty()) { HttpParams params = httpget.getParams(); for (String name : requestParameters.keySet()) { params.setParameter(name, requestParameters.get(name)); } } for (String headerName : requestHeaders.keySet()) { httpget.addHeader(headerName, requestHeaders.get(headerName)); } signRequest(httpget); HttpResponse response = httpclient.execute(httpget); if (!((response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_TEMP) || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_MOVED_PERM) || (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_SEE_OTHER))) { return null; } // redirect location is in location header Header[] locationHeader = response.getHeaders("location"); if (locationHeader.length >= 1) { return locationHeader[0].getValue(); } } catch (IOException e) { throw new MendeleyException(e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); } return null; }
From source file:com.almende.eve.transport.http.ApacheHttpClient.java
/** * Instantiates a new apache http client. * *//* w ww .j a v a2 s. co m*/ private ApacheHttpClient() { // Allow self-signed SSL certificates: final TrustStrategy trustStrategy = new TrustSelfSignedStrategy(); final X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); final SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault(); SSLSocketFactory sslSf; try { sslSf = new SSLSocketFactory(trustStrategy, hostnameVerifier); final Scheme https = new Scheme("https", 443, sslSf); schemeRegistry.register(https); } catch (Exception e) { LOG.warning("Couldn't init SSL socket, https not supported!"); } // Work with PoolingClientConnectionManager final ClientConnectionManager connection = new PoolingClientConnectionManager(schemeRegistry); // Provide eviction thread to clear out stale threads. new Thread(new Runnable() { @Override public void run() { try { while (true) { synchronized (this) { wait(5000); connection.closeExpiredConnections(); connection.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (final InterruptedException ex) { } } }).start(); // generate httpclient httpClient = new DefaultHttpClient(connection); // Set cookie policy and persistent cookieStore try { httpClient.setCookieStore(new MyCookieStore()); } catch (final Exception e) { LOG.log(Level.WARNING, "Failed to initialize persistent cookieStore!", e); } final HttpParams params = httpClient.getParams(); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); params.setParameter(CoreConnectionPNames.TCP_NODELAY, true); httpClient.setParams(params); }