List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:babybear.akbquiz.ConfigActivity.java
/** * ?http/* w w w.j ava2 s . co m*/ * * @param url * @return * @throws Exception */ public String getURLContent(String url) throws Exception { StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); // ? HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } reader.close(); } return sb.toString(); }
From source file:org.instagram4j.DefaultInstagramClient.java
private <T> Result<T> requestEntity(HttpRequestBase method, Class<T> type, boolean signableRequest) throws InstagramException { method.getParams().setParameter("http.useragent", "Instagram4j/1.0"); JsonParser jp = null;/*from w w w .j a v a 2 s. co m*/ HttpResponse response = null; ResultMeta meta = null; try { method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); if (signableRequest) setEnforceHeader(method); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000); if (LOG.isDebugEnabled()) LOG.debug(String.format("Requesting entity entry point %s, method %s", method.getURI().toString(), method.getMethod())); autoThrottle(); response = client.execute(method); jp = createParser(response, method); JsonToken tok = jp.nextToken(); if (tok != JsonToken.START_OBJECT) { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); throw createInstagramException("Invalid response format from Instagram API", method.getURI().toString(), response, null, null); } T data = null; while (true) { tok = jp.nextValue(); if (tok == JsonToken.START_ARRAY) { throw createInstagramException("Unexpected array in entity response " + jp.getCurrentName(), method.getURI().toString(), response, meta, null); } else if (tok == JsonToken.START_OBJECT) { // Should be "data" or "meta" String name = jp.getCurrentName(); if ("meta".equals(name)) meta = jp.readValueAs(ResultMeta.class); else if ("data".equals(name)) { if (type != null) data = jp.readValueAs(type); else jp.readValueAs(Map.class); // Consume & ignore } else throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); } else break; } if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); Result<T> result = new Result<T>(null, meta, data); setRateLimits(response, result); return result; } catch (JsonParseException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (JsonProcessingException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (IOException e) { throw createInstagramException("Error communicating with Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } finally { if (jp != null) try { jp.close(); } catch (IOException e) { } method.releaseConnection(); } }
From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java
private void initialize() { HttpClient client = new DefaultHttpClient(); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(client.getParams(), client.getConnectionManager().getSchemeRegistry()), client.getParams()); }
From source file:org.instagram4j.DefaultInstagramClient.java
@SuppressWarnings("unchecked") private <T> Result<T[]> requestEntities(HttpRequestBase method, Class<T> type) throws InstagramException { method.getParams().setParameter("http.useragent", "Instagram4j/1.0"); JsonParser jp = null;//from w ww . ja va 2s. c o m HttpResponse response = null; ResultMeta meta = null; try { method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); setEnforceHeader(method); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000); if (LOG.isDebugEnabled()) LOG.debug(String.format("Requesting entities entry point %s, method %s", method.getURI().toString(), method.getMethod())); autoThrottle(); response = client.execute(method); jp = createParser(response, method); JsonToken tok = jp.nextToken(); if (tok != JsonToken.START_OBJECT) { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); throw createInstagramException("Invalid response format from Instagram API", method.getURI().toString(), response, null, null); } Pagination pagination = null; T[] data = null; while (true) { tok = jp.nextValue(); if (tok == JsonToken.START_ARRAY) { // Should be "data" String name = jp.getCurrentName(); if (!"data".equals(name)) throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); List<T> items = new ArrayList<T>(); tok = jp.nextToken(); if (tok == JsonToken.START_OBJECT) { if (type != null) { T item; while ((item = jp.readValueAs(type)) != null) items.add(item); } else jp.readValueAs(Map.class); // Consume & ignore } data = (T[]) Array.newInstance(type, items.size()); System.arraycopy(items.toArray(), 0, data, 0, items.size()); } else if (tok == JsonToken.START_OBJECT) { // Should be "pagination" or "meta" String name = jp.getCurrentName(); if ("pagination".equals(name)) pagination = jp.readValueAs(Pagination.class); else if ("meta".equals(name)) meta = jp.readValueAs(ResultMeta.class); else throw createInstagramException("Unexpected field name " + name, method.getURI().toString(), response, meta, null); } else break; } if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw createInstagramException("Instagram request failed", method.getURI().toString(), response, null, null); Result<T[]> result = new Result<T[]>(pagination, meta, data); setRateLimits(response, result); return result; } catch (JsonParseException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (JsonProcessingException e) { throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } catch (IOException e) { throw createInstagramException("Error communicating with Instagram: " + e.getMessage(), method.getURI().toString(), response, meta, e); } finally { if (jp != null) try { jp.close(); } catch (IOException e) { } method.releaseConnection(); } }
From source file:org.jboss.as.test.integration.web.security.cert.WebSecurityCERTTestCase.java
public static HttpClient wrapClient(HttpClient base, String alias) { try {/*from w w w. j ava 2 s .c o m*/ SSLContext ctx = SSLContext.getInstance("TLS"); JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert"); jsseSecurityDomain.setKeyStorePassword("changeit"); ClassLoader tccl = Thread.currentThread().getContextClassLoader(); URL keystore = tccl.getResource("security/client.keystore"); jsseSecurityDomain.setKeyStoreURL(keystore.getPath()); jsseSecurityDomain.setClientAlias(alias); jsseSecurityDomain.reloadKeyAndTrustStore(); KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers(); TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers(); ctx.init(keyManagers, trustManagers, null); X509HostnameVerifier verifier = new X509HostnameVerifier() { @Override public void verify(String s, SSLSocket sslSocket) throws IOException { } @Override public void verify(String s, X509Certificate x509Certificate) throws SSLException { } @Override public void verify(String s, String[] strings, String[] strings1) throws SSLException { } @Override public boolean verify(String string, SSLSession ssls) { return true; } }; SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 8380, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:eu.liveandgov.ar.utilities.RestClient.java
private void executeRequest(HttpUriRequest request, String url, int soTime, int connTime) { HttpClient client = new DefaultHttpClient(); //----- Set timeout -------------- // HttpParams httpParameters = new BasicHttpParams(); // // www . j a v a 2 s.co m // // Set the timeout in milliseconds until a connection is established. // // The default value is zero, that means the timeout is not used. // int timeoutConnection = 1000; // HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // // Set the default socket timeout (SO_TIMEOUT) // // in milliseconds which is the timeout for waiting for data. // int timeoutSocket = 1000; // HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.getParams().setParameter("http.socket.timeout", soTime); client.getParams().setParameter("http.connection.timeout", connTime); //---------------------------------- HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } }
From source file:de.madvertise.android.sdk.MadView.java
/** * Starts a background thread to fetch a new ad. Method is called * from the refresh timer task/*from w w w .ja v a 2 s . com*/ */ private void requestNewAd() { MadUtil.logMessage(null, Log.DEBUG, "Trying to fetch a new ad"); // exit if already requesting a new ad, not used yet if (runningRefreshAd) { MadUtil.logMessage(null, Log.DEBUG, "Another request is still in progress ..."); return; } new Thread() { public void run() { // read all parameters, that we need for the request // get site token from manifest xml file String siteToken = MadUtil.getToken(getContext()); if (siteToken == null) { siteToken = ""; MadUtil.logMessage(null, Log.DEBUG, "Cannot show ads, since the appID ist null"); } else { MadUtil.logMessage(null, Log.DEBUG, "appID = " + siteToken); } // get uid (does not work in emulator) String uid = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID); if (uid == null) { uid = ""; } else { uid = getMD5Hash(uid); } MadUtil.logMessage(null, Log.DEBUG, "uid = " + uid); // get display metrics Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int displayHeight = display.getHeight(); int displayWidth = display.getWidth(); MadUtil.logMessage(null, Log.DEBUG, "Display height = " + Integer.toString(displayHeight)); MadUtil.logMessage(null, Log.DEBUG, "Display width = " + Integer.toString(displayWidth)); // create post request HttpPost postRequest = new HttpPost(MadUtil.MAD_SERVER + "/site/" + siteToken); postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); List<NameValuePair> parameterList = new ArrayList<NameValuePair>(); parameterList.add(new BasicNameValuePair("ua", MadUtil.getUA())); parameterList.add(new BasicNameValuePair("app", "true")); parameterList.add(new BasicNameValuePair("debug", Boolean.toString(testMode))); parameterList.add(new BasicNameValuePair("ip", MadUtil.getLocalIpAddress())); parameterList.add(new BasicNameValuePair("format", "json")); parameterList.add(new BasicNameValuePair("requester", "android_sdk")); parameterList.add(new BasicNameValuePair("version", "1.1")); parameterList.add(new BasicNameValuePair("uid", uid)); parameterList.add(new BasicNameValuePair("banner_type", bannerType)); parameterList.add(new BasicNameValuePair("deliver_only_text", Boolean.toString(deliverOnlyText))); MadUtil.refreshCoordinates(getContext()); if (MadUtil.getLocation() != null) { parameterList.add( new BasicNameValuePair("lat", Double.toString(MadUtil.getLocation().getLatitude()))); parameterList.add( new BasicNameValuePair("lng", Double.toString(MadUtil.getLocation().getLongitude()))); } UrlEncodedFormEntity urlEncodedEntity = null; try { urlEncodedEntity = new UrlEncodedFormEntity(parameterList); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postRequest.setEntity(urlEncodedEntity); MadUtil.logMessage(null, Log.DEBUG, "Post request created"); MadUtil.logMessage(null, Log.DEBUG, "Uri : " + postRequest.getURI().toASCIIString()); MadUtil.logMessage(null, Log.DEBUG, "All headers : " + MadUtil.getAllHeadersAsString(postRequest.getAllHeaders())); MadUtil.logMessage(null, Log.DEBUG, "All request parameters :" + MadUtil.printRequestParameters(parameterList)); synchronized (this) { // send blocking request to ad server HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = null; InputStream inputStream = null; boolean jsonFetched = false; JSONObject json = null; try { HttpParams clientParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(clientParams, MadUtil.CONNECTION_TIMEOUT.intValue()); HttpConnectionParams.setSoTimeout(clientParams, MadUtil.CONNECTION_TIMEOUT.intValue()); MadUtil.logMessage(null, Log.DEBUG, "Sending request"); httpResponse = httpClient.execute(postRequest); MadUtil.logMessage(null, Log.DEBUG, "Response Code => " + httpResponse.getStatusLine().getStatusCode()); if (testMode) MadUtil.logMessage(null, Log.DEBUG, "Madvertise Debug Response: " + httpResponse.getLastHeader("X-Madvertise-Debug")); int responseCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity entity = httpResponse.getEntity(); if (responseCode == 200 && entity != null) { inputStream = entity.getContent(); String resultString = MadUtil.convertStreamToString(inputStream); MadUtil.logMessage(null, Log.DEBUG, "Response => " + resultString); json = new JSONObject(resultString); jsonFetched = true; } } catch (ClientProtocolException e) { e.printStackTrace(); MadUtil.logMessage(null, Log.DEBUG, "Error in HTTP request / protocol"); } catch (IOException e) { e.printStackTrace(); MadUtil.logMessage(null, Log.DEBUG, "Could not receive a http response on an ad reqeust"); } catch (JSONException e) { e.printStackTrace(); MadUtil.logMessage(null, Log.DEBUG, "Could not parse json object"); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { } } // create ad, this is a blocking call if (jsonFetched) { currentAd = new Ad(getContext(), json); } } mHandler.post(mUpdateResults); } }.start(); }
From source file:org.madsonic.service.PodcastService.java
private void doDownloadEpisode(PodcastEpisode episode) { InputStream in = null;/*ww w. java 2 s. c o m*/ OutputStream out = null; if (isEpisodeDeleted(episode)) { LOG.info("Podcast " + episode.getUrl() + " was deleted. Aborting download."); return; } LOG.info("Starting to download Podcast from " + episode.getUrl()); HttpClient client = new DefaultHttpClient(); try { if (!settingsService.getLicenseInfo().isLicenseOrTrialValid()) { // throw new Exception("Sorry, the trial period is expired."); } PodcastChannel channel = getChannel(episode.getChannelId()); HttpConnectionParams.setConnectionTimeout(client.getParams(), 2 * 60 * 1000); // 2 minutes HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 60 * 1000); // 10 minutes HttpGet method = new HttpGet(episode.getUrl()); HttpResponse response = client.execute(method); in = response.getEntity().getContent(); File file = getFile(channel, episode); out = new FileOutputStream(file); episode.setStatus(PodcastStatus.DOWNLOADING); episode.setBytesDownloaded(0L); episode.setErrorMessage(null); episode.setPath(file.getPath()); podcastDao.updateEpisode(episode); byte[] buffer = new byte[4096]; long bytesDownloaded = 0; int n; long nextLogCount = 30000L; while ((n = in.read(buffer)) != -1) { out.write(buffer, 0, n); bytesDownloaded += n; if (bytesDownloaded > nextLogCount) { episode.setBytesDownloaded(bytesDownloaded); nextLogCount += 30000L; // Abort download if episode was deleted by user. if (isEpisodeDeleted(episode)) { break; } podcastDao.updateEpisode(episode); } } if (isEpisodeDeleted(episode)) { LOG.info("Podcast " + episode.getUrl() + " was deleted. Aborting download."); IOUtils.closeQuietly(out); file.delete(); } else { addMediaFileIdToEpisodes(Arrays.asList(episode)); episode.setBytesDownloaded(bytesDownloaded); podcastDao.updateEpisode(episode); LOG.info("Downloaded " + bytesDownloaded + " bytes from Podcast " + episode.getUrl()); IOUtils.closeQuietly(out); try { updateTags(file, episode); } catch (Exception x) { LOG.warn("Failed to update tags for podcast " + episode.getUrl(), x); } episode.setStatus(PodcastStatus.COMPLETED); podcastDao.updateEpisode(episode); deleteObsoleteEpisodes(channel); } } catch (Exception x) { LOG.warn("Failed to download Podcast from " + episode.getUrl(), x); episode.setStatus(PodcastStatus.ERROR); episode.setErrorMessage(getErrorMessage(x)); podcastDao.updateEpisode(episode); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); client.getConnectionManager().shutdown(); } }
From source file:com.android.picasaphotouploader.ImageUploader.java
/** * Upload image to Picasa// w w w . jav a 2 s . c o m */ public void run() { // create items for http client UploadNotification notification = new UploadNotification(context, item.imageId, item.imageSize, item.imageName); String url = "http://picasaweb.google.com/data/feed/api/user/" + item.prefs.getString("email", "") + "/albumid/" + item.prefs.getString("album", ""); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); try { // new file and and entity File file = new File(item.imagePath); Multipart multipart = new Multipart("Media multipart posting", "END_OF_PART"); // create entity parts multipart.addPart("<entry xmlns='http://www.w3.org/2005/Atom'><title>" + item.imageName + "</title><category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/photos/2007#photo\"/></entry>", "application/atom+xml"); multipart.addPart(file, item.imageType); // create new Multipart entity MultipartNotificationEntity entity = new MultipartNotificationEntity(multipart, notification); // get http params HttpParams params = client.getParams(); // set protocal and timeout for httpclient params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(15000)); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(15000)); // set body with upload entity post.setEntity(entity); // set headers post.addHeader("Authorization", "GoogleLogin auth=" + item.imageAuth); post.addHeader("GData-Version", "2"); post.addHeader("MIME-version", "1.0"); // execute upload to picasa and get response and status HttpResponse response = client.execute(post); StatusLine line = response.getStatusLine(); // return code indicates upload failed so throw exception if (line.getStatusCode() > 201) { throw new Exception("Failed upload"); } // shut down connection client.getConnectionManager().shutdown(); // notify user that file has been uploaded notification.finished(); } catch (Exception e) { // file upload failed so abort post and close connection post.abort(); client.getConnectionManager().shutdown(); // get user preferences and number of retries for failed upload SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int maxRetries = Integer.valueOf(prefs.getString("retries", "").substring(1)); // check if we can connect to internet and if we still have any tries left // to try upload again if (CheckInternet.getInstance().canConnect(context, prefs) && retries < maxRetries) { // remove notification for failed upload and queue item again notification.remove(); queue.execute(new ImageUploader(context, queue, item, retries++)); } else { // upload failed, so let's notify user notification.failed(); } } }
From source file:com.pongme.utils.ImageDownloader.java
protected HttpClient getHttpClient() { HttpClient client = null; if (mode != Mode.NO_ASYNC_TASK || ANDROID_CLIENT_CLASS != null) { try {// ww w.j a va2 s .c o m client = (HttpClient) ANDROID_CLIENT_CONSTRUCTOR.invoke(null, "Android"); } catch (Exception e) { } } else client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "USER-AGENT"); return client; }