List of usage examples for org.apache.http.impl.client DefaultHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:com.servoy.extensions.plugins.http.HttpProvider.java
public static void main(String[] args) throws Exception { if (args.length != 3) { System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$ System.out.println(//from w ww. j a v a 2 s .c o m "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$ System.out.println( "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$ } else { String url = args[1]; String destdir = args[2]; List parts = new ArrayList(); int dir_from = 0; int dir_to = 0; int dir_fill = 0; int from = 0; int to = 0; int fill = 0; StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$ boolean hasDir = (tk.countTokens() > 5); boolean inDir = hasDir; System.out.println("hasDir " + hasDir); //$NON-NLS-1$ boolean inTag = false; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("[")) //$NON-NLS-1$ { inTag = true; continue; } if (token.equals("]")) //$NON-NLS-1$ { inTag = false; if (inDir) inDir = false; continue; } if (inTag) { int idx = token.indexOf('-'); String s_from = token.substring(0, idx); int a_from = new Integer(s_from).intValue(); int a_fill = s_from.length(); int a_to = new Integer(token.substring(idx + 1)).intValue(); if (inDir) { dir_from = a_from; dir_to = a_to; dir_fill = a_fill; } else { from = a_from; to = a_to; fill = a_fill; } } else { parts.add(token); } } DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpGet main = new HttpGet(args[0]); HttpResponse res = client.execute(main); ; int main_rs = res.getStatusLine().getStatusCode(); if (main_rs != 200) { System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$ return; } for (int d = dir_from; d <= dir_to; d++) { String dir_number = "" + d; //$NON-NLS-1$ if (dir_fill > 1) { dir_number = "000000" + d; //$NON-NLS-1$ int dir_digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$ dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits), dir_number.length()); } for (int i = from; i <= to; i++) { try { String number = "" + i; //$NON-NLS-1$ if (fill > 1) { number = "000000" + i; //$NON-NLS-1$ int digits = (int) (Math.log(fill) / Math.log(10)); System.out.println("digits " + digits); //$NON-NLS-1$ number = number.substring(number.length() - (fill - digits), number.length()); } int part = 0; StringBuffer surl = new StringBuffer((String) parts.get(part++)); if (hasDir) { surl.append(dir_number); surl.append(parts.get(part++)); } surl.append(number); surl.append(parts.get(part++)); System.out.println("reading url " + surl); //$NON-NLS-1$ int indx = surl.toString().lastIndexOf('/'); StringBuffer sfile = new StringBuffer(destdir); sfile.append("\\"); //$NON-NLS-1$ if (hasDir) { sfile.append("dir_"); //$NON-NLS-1$ sfile.append(dir_number); sfile.append("_"); //$NON-NLS-1$ } sfile.append(surl.toString().substring(indx + 1)); File file = new File(sfile.toString()); if (file.exists()) { file = new File("" + System.currentTimeMillis() + sfile.toString()); } System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$ // URL iurl = createURLFromString(surl.toString()); HttpGet get = new HttpGet(surl.toString()); HttpResponse response = client.execute(get); int result = response.getStatusLine().getStatusCode(); System.out.println("page http result " + result); //$NON-NLS-1$ if (result == 200) { InputStream is = response.getEntity().getContent(); FileOutputStream fos = new FileOutputStream(file); Utils.streamCopy(is, fos); fos.close(); } } catch (Exception e) { System.err.println(e); } } } } }
From source file:mai.cn.film.auth.ClientAuthentication.java
public static void main(String[] args) throws Exception { HttpHost targetHost = new HttpHost("www.filmaffinity.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from ww w . j a v a 2 s .c o m*/ httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("picarus", "8C8PPkEc")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("http://www.filmaffinity.com/en/myvotes.php"); System.out.println("executing request" + httpget.getRequestLine()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); HttpResponse response = httpclient.execute(httpget); String responseBody = responseHandler.handleResponse(response); int code = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); System.out.println("----------------------------------------"); System.out.println("Status:" + code + " " + response.getStatusLine().getReasonPhrase()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.hilatest.httpclient.apacheexample.ClientGZipContentCompression.java
public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); }/* w w w . j av a 2s . c o m*/ } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(response.getLastHeader("Content-Encoding")); System.out.println(response.getLastHeader("Content-Length")); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity); System.out.println(content); System.out.println("----------------------------------------"); System.out.println("Uncompressed size: " + content.length()); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
From source file:com.dlmu.heipacker.crawler.client.ClientGZipContentCompression.java
public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/* w w w .ja v a2 s . c o m*/ httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(response.getLastHeader("Content-Encoding")); System.out.println(response.getLastHeader("Content-Length")); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity); System.out.println(content); System.out.println("----------------------------------------"); System.out.println("Uncompressed size: " + content.length()); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.mumod.util.MustardUtil.java
public static void snapshot(Context context, String id, String version, String accountNumber) { try {//w w w . j a v a 2 s . c o m HttpPost post = new HttpPost("http://mustard.macno.org/snapshot.php"); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("v", version)); params.add(new BasicNameValuePair("n", accountNumber)); params.add(new BasicNameValuePair("m", id)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpManager hm = new HttpManager(context); DefaultHttpClient hc = hm.getHttpClient(); hc.execute(post); } catch (Exception e) { } }
From source file:Main.java
@SuppressWarnings("deprecation") public static InputStream openHttpConnection(String urlString) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet request = new HttpGet(urlString); HttpResponse response = httpClient.execute(request); return response.getEntity().getContent(); }
From source file:Main.java
private static String reverseGeocode(String url) { try {//from ww w .j a va 2 s .co m HttpGet httpGet = new HttpGet(url); BasicHttpParams httpParams = new BasicHttpParams(); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { String charSet = EntityUtils.getContentCharSet(httpResponse.getEntity()); if (null == charSet) { charSet = "UTF-8"; } String str = new String(EntityUtils.toByteArray(httpResponse.getEntity()), charSet); defaultHttpClient.getConnectionManager().shutdown(); return str; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.solrsystem.Main.java
public static boolean doGetToFile(String url, String localFilePath, DownloadStatusListener listener) throws HttpException, IOException { final HttpGet request = new HttpGet(url); final HttpResponse resp; try {//from w w w . j a v a 2 s . co m DefaultHttpClient httpClient = new DefaultHttpClient(); resp = httpClient.execute(request); long totalnum = resp.getEntity().getContentLength(); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { FileOutputStream out = new FileOutputStream(localFilePath); InputStream inputStream = resp.getEntity().getContent(); long bytesRead = 0; int bufferSize = listener.progressInterval(); byte b[] = new byte[bufferSize]; int cnt; System.out.println("reading " + bufferSize); while ((cnt = inputStream.read(b)) != -1) { out.write(b, 0, cnt); bytesRead += cnt; listener.onProgress(bytesRead, totalnum); } out.flush(); out.close(); //resp.getEntity().writeTo(out); out.close(); return true; } else { System.out.println("Download Failed:" + resp.getStatusLine()); return false; } } catch (final IOException e) { e.printStackTrace(); throw new HttpException("IOException " + e.toString()); } }
From source file:Main.java
public static String reverseGeocode(String url) { try {/*from w w w . j a v a2 s . c o m*/ HttpGet httpGet = new HttpGet(url); BasicHttpParams httpParams = new BasicHttpParams(); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { String charSet = EntityUtils.getContentCharSet(httpResponse.getEntity()); if (null == charSet) { charSet = "UTF-8"; } String str = new String(EntityUtils.toByteArray(httpResponse.getEntity()), charSet); defaultHttpClient.getConnectionManager().shutdown(); Log.i("-----------", "str = " + str); return str; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.splunk.shuttl.testutil.TUtilsEndToEnd.java
private static HttpResponse executeHttp(HttpPost httpPost, DefaultHttpClient httpClient) { try {// w ww . j a v a2 s.com return httpClient.execute(httpPost); } catch (IOException e) { throw new RuntimeException(e); } }