List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.reelfx.model.PostProcessor.java
public void run() { try {/*from ww w . j a v a 2s . c om*/ String ffmpeg = "ffmpeg" + (Applet.IS_WINDOWS ? ".exe" : ""); // ----- quickly merge audio and video after recording ----------------------- if (outputFile != null && encodingOpts.containsKey(MERGE_AUDIO_VIDEO) && !Applet.IS_MAC) { fireProcessUpdate(ENCODING_STARTED); // get information about the media file: //Map<String,Object> metadata = parseMediaFile(ScreenRecorder.OUTPUT_FILE.getAbsolutePath()); //printMetadata(metadata); List<String> ffmpegArgs = new ArrayList<String>(); ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg); ffmpegArgs.add("-y"); // overwrite any existing file // audio and video files if (AudioRecorder.OUTPUT_FILE.exists()) { // if opted for microphone // delay the audio if needed ( http://howto-pages.org/ffmpeg/#delay ) if (encodingOpts.containsKey(OFFSET_AUDIO)) ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_AUDIO))); // assume offset is less than 10 seconds ffmpegArgs.addAll(parseParameters("-i " + AudioRecorder.OUTPUT_FILE.getAbsolutePath())); // delay the video if needed ( http://howto-pages.org/ffmpeg/#delay ) if (encodingOpts.containsKey(OFFSET_VIDEO)) ffmpegArgs.addAll(parseParameters("-itsoffset 00:00:0" + encodingOpts.get(OFFSET_VIDEO))); } ffmpegArgs.addAll(parseParameters("-i " + ScreenRecorder.OUTPUT_FILE)); // export settings ffmpegArgs.addAll(getFfmpegCopyParams()); // resize screen //ffmpegArgs.addAll(parseParameters("-s 1024x"+Math.round(1024.0/(double)Applet.SCREEN.width*(double)Applet.SCREEN.height))); ffmpegArgs.add(outputFile.getAbsolutePath()); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); ffmpegProcess = pb.start(); errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); errorGobbler.start(); inputGobbler.start(); ffmpegProcess.waitFor(); logger.info("Done encoding..."); fireProcessUpdate(ENCODING_COMPLETE); } // end merging audio/video // ----- encode file to X264 ----------------------- else if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC && !DEFAULT_OUTPUT_FILE.exists()) { fireProcessUpdate(ENCODING_STARTED); File inputFile = Applet.IS_LINUX ? LinuxController.MERGED_OUTPUT_FILE : WindowsController.MERGED_OUTPUT_FILE; // get information about the media file: //metadata = parseMediaFile(inputFile.getAbsolutePath()); //printMetadata(metadata); List<String> ffmpegArgs = new ArrayList<String>(); ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + ffmpeg); ffmpegArgs.addAll(parseParameters("-y -i " + inputFile.getAbsolutePath())); ffmpegArgs.addAll(getFfmpegX264FastFirstPastBaselineParams()); ffmpegArgs.add(DEFAULT_OUTPUT_FILE.getAbsolutePath()); logger.info("Executing this command: " + prettyCommand(ffmpegArgs)); ProcessBuilder pb = new ProcessBuilder(ffmpegArgs); ffmpegProcess = pb.start(); errorGobbler = new StreamGobbler(ffmpegProcess.getErrorStream(), false, "ffmpeg E"); inputGobbler = new StreamGobbler(ffmpegProcess.getInputStream(), false, "ffmpeg O"); logger.info("Starting listener threads..."); //errorGobbler.addActionListener("frame", this); errorGobbler.start(); inputGobbler.start(); ffmpegProcess.waitFor(); logger.info("Done encoding..."); fireProcessUpdate(ENCODING_COMPLETE); } // do we need to copy the X264 encoded file somewhere? if (outputFile != null && encodingOpts.containsKey(ENCODE_TO_X264) && !Applet.IS_MAC && !outputFile.getAbsolutePath().equals(DEFAULT_OUTPUT_FILE.getAbsolutePath())) { FileUtils.copyFile(DEFAULT_OUTPUT_FILE, outputFile); fireProcessUpdate(ENCODING_COMPLETE); } // ----- just copy the file if it's a Mac ----------------------- if (outputFile != null && Applet.IS_MAC) { FileUtils.copyFile(ScreenRecorder.OUTPUT_FILE, outputFile); fireProcessUpdate(ENCODING_COMPLETE); } try { // ----- post data of screen capture to Insight ----------------------- if (postRecording) { // base code: http://stackoverflow.com/questions/1067655/how-to-upload-a-file-using-java-httpclient-library-working-with-php-strange-pro fireProcessUpdate(POST_STARTED); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); CountingMultipartEntity entity = new CountingMultipartEntity(); ContentBody body = new FileBody(outputFile, "video/quicktime"); entity.addPart("capture_file", body); HttpPost post = new HttpPost(postUrl); post.setEntity(entity); logger.info("Posting file to server... " + post.getRequestLine()); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); logger.info("Response Status Code: " + response.getStatusLine()); if (responseEntity != null) { logger.info(EntityUtils.toString(responseEntity)); // to see the response body } // redirection to show page (meaning everything was correct); NOTE: Insight redirects you to the login form when you're not logged in (or no api_key) //if(response.getStatusLine().getStatusCode() == 302) { //Header header = response.getFirstHeader("Location"); //logger.info("Redirecting to "+header.getValue()); //Applet.redirectWebPage(header.getValue()); //Applet.APPLET.showDocument(new URL(header.getValue()),"_self"); if (response.getStatusLine().getStatusCode() == 200) { fireProcessUpdate(POST_COMPLETE); } else { fireProcessUpdate(POST_FAILED); } if (responseEntity != null) { responseEntity.consumeContent(); } client.getConnectionManager().shutdown(); } // ----- post data of screen capture to Insight ----------------------- else if (postData) { fireProcessUpdate(POST_STARTED); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(postUrl); logger.info("Sending data to Insight... " + post.getRequestLine()); HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); logger.info("Response Status Code: " + response.getStatusLine()); if (responseEntity != null) { logger.info(EntityUtils.toString(responseEntity)); // to see the response body } if (response.getStatusLine().getStatusCode() == 200) { fireProcessUpdate(POST_COMPLETE); } else { fireProcessUpdate(POST_FAILED); } if (responseEntity != null) { responseEntity.consumeContent(); } client.getConnectionManager().shutdown(); } // TODO monitor the progress of the transcoding? // TODO allow canceling of the transcoding? } catch (Exception e) { logger.error("Error occurred while posting the file.", e); fireProcessUpdate(POST_FAILED); } finally { outputFile = null; encodingOpts = new HashMap<Integer, String>(); // reset encoding options metadata = null; } } catch (Exception e) { logger.error("Error occurred while encoding the file.", e); fireProcessUpdate(ENCODING_FAILED); } }
From source file:hornet.framework.technical.HTTPClientParameterBuilderTest.java
/** * Teste la mthode <tt>loadHttpParamToHttpClient</tt>. *///from w w w.ja v a2 s .co m @Test public void testLoadHttpParamToHttpClientBooleanParameter() { final HttpClient httpClient = new DefaultHttpClient(); final String property = "http.protocol.unambiguous-statusline"; final Properties properties = new Properties(); properties.put(property, "true"); HTTPClientParameterBuilder.loadHttpParamToHttpClient(httpClient, properties); assertTrue(httpClient.getParams().getBooleanParameter(property, false)); }
From source file:org.owasp.goatdroid.herdfinancial.requestresponse.RestClient.java
private void executeRequest(HttpUriRequest request, String url, Context context) { HttpClient client = CustomSSLSocketFactory.getNewHttpClient(); HashMap<String, String> proxyInfo = Utils.getProxyMap(context); String proxyHost = proxyInfo.get("proxyHost"); String proxyPort = proxyInfo.get("proxyPort"); if (!(proxyHost.equals("") || proxyPort.equals(""))) { HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }//from www. ja va 2 s.com 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(); } catch (IOException e) { client.getConnectionManager().shutdown(); } }
From source file:com.dongfang.dicos.sina.UtilSina.java
public static HttpClient getNewHttpClient(Context context) { try {/*from w w w . j av a2 s .c om*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, UtilSina.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, UtilSina.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // ??APN Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // ??? String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
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 ww w. j a v a2s . c o m 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:org.codehaus.httpcache4j.resolver.HTTPClientResponseResolver.java
public HTTPClientResponseResolver(HttpClient httpClient, ProxyAuthenticator proxyAuthenticator, Authenticator authenticator) { super(proxyAuthenticator, authenticator); this.httpClient = httpClient; HTTPHost proxyHost = proxyAuthenticator.getConfiguration().getHost(); if (proxyHost != null) { HttpHost host = new HttpHost(proxyHost.getHost(), proxyHost.getPort(), proxyHost.getScheme()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host); }/* w ww . j a v a 2 s . c om*/ }
From source file:org.owasp.goatdroid.herdfinancial.requestresponse.AuthenticatedRestClient.java
private void executeRequest(HttpUriRequest request, String url, Context context) throws KeyManagementException, NoSuchAlgorithmException { HttpClient client = CustomSSLSocketFactory.getNewHttpClient(); HashMap<String, String> proxyInfo = Utils.getProxyMap(context); String proxyHost = proxyInfo.get("proxyHost"); String proxyPort = proxyInfo.get("proxyPort"); if (!(proxyHost.equals("") || proxyPort.equals(""))) { HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }//w w w .j av a 2s .co m 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); instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); } catch (IOException e) { client.getConnectionManager().shutdown(); } }
From source file:de.fhg.iais.asc.oai.retriever.MetadataFormatsAndSetNamesRetriever.java
public MetadataFormatsAndSetNamesRetriever(String uri, ASCState ascstate, String proxyhost, Integer proxyport) { this.uri = uri; this.ascstate = ascstate; HttpClient client = new DefaultHttpClient(); // set some parameters that might help but will not harm // see: http://hc.apache.org/httpclient-legacy/preference-api.html // the user-agent: // tell them who we are (they see that from the IP anyway), thats a good habit, // shows that we are professional and not some script kiddies // and this is also a little bit of viral marketing :-) client.getParams().setParameter("http.useragent", "myCortex Harvester; http://www.iais.fraunhofer.de/"); // the following option "can result in noticeable performance improvement" (see api docs) // it may switch on a keep-alive, may reduce load on server side (if they are smart) // and might reduce latency client.getParams().setParameter("http.protocol.expect-continue", true); // ignore all cookies because some OAI-PMH implementations don't know how to handle cookies client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); // setting of the proxy if needed if (proxyhost != null && !proxyhost.isEmpty()) { HttpHost proxy = new HttpHost(proxyhost, proxyport); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); }/* w w w.j a v a2s . com*/ this.server = new OaiPmhServer(client, this.uri); }
From source file:com.firescar96.nom.GCMIntentService.java
/** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP * or CCS to send messages to your app. Not needed for this demo since the * device sends upstream messages to a server that echoes back the message * using the 'from' address in the message. * @return //from ww w . j av a 2 s .c om */ public static String sendRegistrationIdToBackend() { String msg = ""; new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... param) { String msg = ""; InputStream inputStream = null; try { // 1. create HttpClient HttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL HttpPost httpPost = new HttpPost("http://nchinda2.mit.edu:666"); String json = ""; // 3. build jsonObject JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("regId", regId); jsonObject.accumulate("host", MainActivity.appData.getString("host")); // 4. convert JSONObject to JSON to String json = jsonObject.toString(); // 5. set json to StringEntity StringEntity se = new StringEntity(json); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, 5000); httpPost.setParams(httpParams); // 8. Execute POST request to the given URL System.out.println("executing" + json); HttpResponse httpResponse = httpclient.execute(httpPost); // 9. receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // 10. convert inputstream to string if (inputStream != null) msg = convertInputStreamToString(inputStream); else msg = "Did not work!"; } catch (Exception e) { e.printStackTrace(); ; } System.out.println(msg); return msg; } }.execute(null, null, null); System.out.println(msg); return msg; }
From source file:com.basho.riak.client.raw.http.HTTPRiakClientFactoryTest.java
/** * Test method for/* w ww . ja va2s .c om*/ * {@link com.basho.riak.client.raw.http.HTTPRiakClientFactory#newClient(com.basho.riak.client.raw.config.Configuration)} * . * * @throws IOException */ @Test public void newClientIsConfigured() throws IOException { HTTPClientConfig.Builder b = new HTTPClientConfig.Builder(); HttpClient httpClient = mock(HttpClient.class); HttpParams httpParams = mock(HttpParams.class); HttpResponse response = mock(HttpResponse.class); HttpEntity entity = mock(HttpEntity.class); when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(response); when(response.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); when(response.getEntity()).thenReturn(entity); when(httpClient.getParams()).thenReturn(httpParams); HTTPClientConfig conf = b.withUrl("http://www.google.com/notriak").withHttpClient(httpClient) .withMapreducePath("/notAPath").withMaxConnctions(200).withTimeout(9000).build(); HTTPClientAdapter client = (HTTPClientAdapter) HTTPRiakClientFactory.getInstance().newClient(conf); verify(httpParams).setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 9000); verify(httpParams).setIntParameter(AllClientPNames.SO_TIMEOUT, 9000); client.delete("b", "k"); verify(httpClient).execute(any(HttpDelete.class)); }