List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams
public BasicHttpParams()
From source file:bkampfbot.Utils.java
public final static boolean fightAvailable(int retry) { for (int i = retry; i > 0; i--) { if (i != retry) { Control.sleep(600);/*ww w. ja v a 2 s. c om*/ Output.println(" - versuche erneut", 1); } try { // HTTP parameters stores header etc. HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); HttpGet httpget = new HttpGet(Config.getHost() + "fights/start"); httpget.setParams(params); HttpResponse response = Control.current.httpclient.execute(httpget); // obtain redirect target Header locationHeader = response.getFirstHeader("location"); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } if (locationHeader == null) { return true; } } catch (IOException e) { } Output.printTab("Kampf nicht verfgbar", 1); } Output.println(" - Abbruch", 1); return false; }
From source file:com.jsquant.listener.JsquantContextListener.java
public void contextInitialized(ServletContextEvent sce) { contextDestroyed(sce);/*ww w . j a v a 2s . c o m*/ ServletContext context = sce.getServletContext(); String fileCachePath = getFileCachePath(context); context.setAttribute(ATTR_FILE_CACHE, new FileCache(fileCachePath)); HttpParams params = new BasicHttpParams(); //params.setParameter("http.useragent", "Mozilla/5.0"); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); final HttpClient httpClient = new DefaultHttpClient(manager, params); //HttpHost proxy = new HttpHost("someproxy.com", 80); //httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); context.setAttribute(ATTR_HTTP_CLIENT, httpClient); }
From source file:de.jetwick.snacktory.HijackableHttpPageReader.java
/** {@inheritDoc}*/ @SuppressWarnings("deprecation") @Override//from w w w. j a v a 2s . co m public String readPage(String url) throws PageReadException { if (url.equals(this.url) && StringUtils.isNotEmpty(pageHtml)) { LOG.info("Use already fetched content of " + url); return pageHtml; } else { LOG.info("Reading " + url); this.url = url; this.pageHtml = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet(url); get.setHeader("User-Agent", userAgent); InputStream response = null; HttpResponse httpResponse = null; try { try { httpResponse = httpclient.execute(get, localContext); int resp = httpResponse.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK != resp) { LOG.error("Download failed of " + url + " status " + resp + " " + httpResponse.getStatusLine().getReasonPhrase()); return null; } String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity()); pageHtml = readContent(httpResponse.getEntity().getContent(), respCharset); return pageHtml; } finally { if (response != null) { response.close(); } if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().consumeContent(); } } } catch (IOException e) { LOG.error("Download failed of " + url, e); throw new PageReadException("Failed to read " + url, e); } } }
From source file:net.ccghe.emocha.async.UploadOneFile.java
public UploadOneFile(String path, String serverURL, FileTransmitter transmitter, MultipartEntity postData) { // configure connection HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 20 * Constants.ONE_SECOND); HttpConnectionParams.setSoTimeout(params, 20 * Constants.ONE_SECOND); HttpClientParams.setRedirecting(params, false); // setup client DefaultHttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(serverURL); int id = 0;/*from w w w. ja va 2 s . c o m*/ postData.addPart("file" + id, new FileBody(new File(path))); try { postData.addPart("path" + id, new StringBody(path)); } catch (UnsupportedEncodingException e1) { Log.e(Constants.LOG_TAG, "Encoding error while uploading file."); } // prepare response and return uploaded try { post.setEntity(postData); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); String jsonResponse = Server.convertStreamToString(stream); stream.close(); if (postData != null) { postData.consumeContent(); } JSONObject jObject = new JSONObject(jsonResponse); Long ok = jObject.getLong("ok"); if (ok > 0) { DBAdapter.markAsUploaded(path); Log.i(Constants.LOG_TAG, "Mark as uploaded: " + path); } else { Log.e(Constants.LOG_TAG, "Error uploading: " + path + " (json response not ok)"); } } catch (ClientProtocolException e) { Log.e("EMOCHA", "ClientProtocolException ERR. " + e.getMessage()); } catch (IOException e) { Log.e("EMOCHA", "IOException ERR. " + e.getMessage()); } catch (Exception e) { Log.e("EMOCHA", "Exception ERR. " + e.getMessage()); } /* // check response. // TODO: This isn't handled correctly. String serverLocation = null; Header[] h = response.getHeaders("Location"); if (h != null && h.length > 0) { serverLocation = h[0].getValue(); } else { // something should be done here... Log.e(Constants.LOG_TAG, "Location header was absent"); } int responseCode = response.getStatusLine().getStatusCode(); Log.e(Constants.LOG_TAG, "Response code:" + responseCode); // verify that your response came from a known server if (serverLocation != null && serverURL.contains(serverLocation) && responseCode == 201) { DBAdapter.markAsUploaded(path); } */ transmitter.transmitComplete(); }
From source file:de.jetwick.snacktory.HttpPageReader.java
/** {@inheritDoc}*/ @SuppressWarnings("deprecation") @Override/*from www . j a v a 2 s . com*/ public String readPage(String url) throws PageReadException { LOG.info("Reading " + url); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet(url); InputStream response = null; HttpResponse httpResponse = null; try { try { httpResponse = httpclient.execute(get, localContext); int resp = httpResponse.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK != resp) { LOG.error("Download failed of " + url + " status " + resp + " " + httpResponse.getStatusLine().getReasonPhrase()); return null; } String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity()); return readContent(httpResponse.getEntity().getContent(), respCharset); } finally { if (response != null) { response.close(); } if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().consumeContent(); } } } catch (IOException e) { LOG.error("Download failed of " + url, e); throw new PageReadException("Failed to read " + url, e); } }
From source file:net.peterkuterna.android.apps.devoxxsched.util.SyncUtils.java
/** * Generate and return a {@link HttpClient} configured for general use, * including setting an application-specific user-agent string. *//* w w w. j a va 2 s.c o m*/ public static HttpClient getHttpClient(Context context) { final HttpParams params = new BasicHttpParams(); // Use generous timeouts for slow mobile networks HttpConnectionParams.setConnectionTimeout(params, 200 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, 200 * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpProtocolParams.setUserAgent(params, buildUserAgent(context)); final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); final SchemeRegistry schemeReg = new SchemeRegistry(); schemeReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeReg.register(new Scheme("https", sslSocketFactory, 443)); final ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeReg); final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { // Add header to accept gzip content if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { // Inflate any responses compressed with gzip final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); return client; }
From source file:org.upm.pregonacid.db.ws.EventWSGetAsyncTask.java
public List<EventDO> listEventszzz(String urlString) { InputStream inputStream = null; URL url = null;// ww w. j av a 2 s. c om HttpURLConnection connection = null; try { url = new URL(urlString); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); connection = (HttpURLConnection) url.openConnection(); //connection.setRequestProperty("User-Agent", ""); //connection.setRequestMethod("GET"); //connection.setDoInput(true); //connection.connect(); inputStream = new BufferedInputStream(connection.getInputStream()); } catch (IOException e) { // Writing exception to log e.printStackTrace(); } finally { connection.disconnect(); } Reader reader = new InputStreamReader(inputStream); Gson gson = new Gson(); EventDOList r = gson.fromJson(reader, EventDOList.class); List<EventDO> events = r.events; return events; }
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String runHttpGetCommand(String url) throws Exception { String return_; DefaultHttpClient client = new DefaultHttpClient(); InputStream isStream = null;/*from www . j a va 2s .c om*/ try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 1000; int timeoutSocket = 1000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.setParams(httpParameters); HttpGet getRequest = new HttpGet(url); getRequest.setHeader("Content-type", "application/json"); HttpResponse resp = client.execute(getRequest); if (resp == null || resp.getEntity() == null) { throw new ESHttpException("Unable to execute GET URL (" + url + ") Exception Message: < Null Response or Null HttpEntity >"); } isStream = resp.getEntity().getContent(); if (resp.getStatusLine().getStatusCode() != 200) { throw new ESHttpException("Unable to execute GET URL (" + url + ") Exception Message: (" + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")"); } return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()); logger.debug("GET URL API: {} returns: {}", url, return_); } catch (Exception e) { throw new ESHttpException( "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")"); } finally { if (isStream != null) isStream.close(); } return return_; }
From source file:com.tejus.shavedog.HttpServer.java
public HttpServer(LocalInetAddressResolver localInetAddressResolver, int listenPort) { this.localInetAddressResolver = localInetAddressResolver; this.listenPort = listenPort; this.handlerRegistry = new HttpRequestHandlerRegistry(); this.params = new BasicHttpParams(); this.params.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "4thLineAndroidHttpServer/1.0") .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); if (Util.ANDROID_EMULATOR) { // Start immediately on emulator because there will never be a "WiFi switched on" event startServer();//from ww w . j av a 2s. c om } }
From source file:com.vuze.android.remote.rpc.RestJsonClient.java
public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers, UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException { long readTime = 0; long connSetupTime = 0; long connTime = 0; int bytesRead = 0; if (DEBUG_DETAILED) { Log.d(TAG, id + "] Execute " + url); }//from w w w.j av a 2s.co m long now = System.currentTimeMillis(); long then; Map<?, ?> json = Collections.EMPTY_MAP; try { URI uri = new URI(url); int port = uri.getPort(); BasicHttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote"); DefaultHttpClient httpclient; if ("https".equals(uri.getScheme())) { httpclient = MySSLSocketFactory.getNewHttpClient(port); } else { httpclient = new DefaultHttpClient(basicHttpParams); } //AndroidHttpClient.newInstance("Vuze Android Remote"); // This doesn't set the "Authorization" header!? httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds); // Prepare a request object HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException if (creds != null) { byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes(); String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length); httpRequest.setHeader("Authorization", "Basic " + encoding); } if (jsonPost != null) { HttpPost post = (HttpPost) httpRequest; String postString = JSONUtils.encodeToJSON(jsonPost); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "] Post: " + postString); } AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getCompressedEntity(postString) : new StringEntity(postString); post.setEntity(entity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { setupRequestFroyo(httpRequest); } if (headers != null) { for (Header header : headers) { httpRequest.setHeader(header); } } // Execute the request HttpResponse response; then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connSetupTime = (then - now); now = then; } httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { if (i < 2) { return true; } return false; } }); response = httpclient.execute(httpRequest); then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connTime = (then - now); now = then; } HttpEntity entity = response.getEntity(); // XXX STATUSCODE! StatusLine statusLine = response.getStatusLine(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "StatusCode: " + statusLine.getStatusCode()); } if (entity != null) { long contentLength = entity.getContentLength(); if (contentLength >= Integer.MAX_VALUE - 2) { throw new RPCException("JSON response too large"); } // A Simple JSON Response Read InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getUngzippedContent(entity) : entity.getContent(); InputStreamReader isr = new InputStreamReader(instream, "utf8"); StringBuilder sb = null; BufferedReader br = null; // JSONReader is 10x slower, plus I get more OOM errors.. :( // final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false // : DEFAULT_USE_STRINGBUFFER; final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER; if (useStringBuffer) { // Setting capacity saves StringBuffer from going through many // enlargeBuffers, and hopefully allows toString to not make a copy sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512); } else { if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "Using BR. ContentLength = " + contentLength); } br = new BufferedReader(isr, 8192); br.mark(32767); } try { // 9775 files on Nexus 7 (~2,258,731 bytes) // fastjson 1.1.46 (String) : 527- 624ms // fastjson 1.1.39 (String) : 924-1054ms // fastjson 1.1.39 (StringBuilder): 1227-1463ms // fastjson 1.1.39 (BR) : 2233-2260ms // fastjson 1.1.39 (isr) : 2312ms // GSON 2.2.4 (String) : 1539-1760ms // GSON 2.2.4 (BufferedReader) : 2646-3060ms // JSON-SMART 1.3.1 (String) : 572- 744ms (OOMs more often than fastjson) if (useStringBuffer) { char c[] = new char[8192]; while (true) { int read = isr.read(c); if (read < 0) { break; } sb.append(c, 0, read); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); if (DEBUG_DETAILED) { if (sb.length() > 2000) { Log.d(TAG, id + "] " + sb.substring(0, 2000) + "..."); } else { Log.d(TAG, id + "] " + sb.toString()); } } bytesRead = sb.length(); readTime = (then - now); now = then; } json = JSONUtils.decodeJSON(sb.toString()); //json = JSONUtilsGSON.decodeJSON(sb.toString()); } else { //json = JSONUtils.decodeJSON(isr); json = JSONUtils.decodeJSON(br); //json = JSONUtilsGSON.decodeJSON(br); } } catch (Exception pe) { // StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 409) { throw new RPCException(response, "409"); } try { String line; if (useStringBuffer) { line = sb.subSequence(0, Math.min(128, sb.length())).toString(); } else { br.reset(); line = br.readLine().trim(); } isr.close(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "]line: " + line); } Header contentType = entity.getContentType(); if (line.startsWith("<") || line.contains("<html") || (contentType != null && contentType.getValue().startsWith("text/html"))) { // TODO: use android strings.xml throw new RPCException(response, "Could not retrieve remote client location information. The most common cause is being on a guest wifi that requires login before using the internet."); } } catch (IOException ignore) { } Log.e(TAG, id, pe); if (statusLine != null) { String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n" + pe.getMessage(); throw new RPCException(msg, pe); } throw new RPCException(pe); } finally { closeOnNewThread(useStringBuffer ? isr : br); } if (AndroidUtils.DEBUG_RPC) { // Log.d(TAG, id + "]JSON Result: " + json); } } } catch (RPCException e) { throw e; } catch (Throwable e) { Log.e(TAG, id, e); throw new RPCException(e); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime + "ms, parsed in " + (then - now) + "ms"); } return json; }