List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:org.vsepml.storm.sensapp.RestRequest.java
public static boolean isSensorRegistred(Sensor sensor) { URI target = null;/*from w ww.j a v a 2s . c o m*/ try { target = new URI(sensor.getUri().toString() + SENSOR_PATH + "/" + sensor.getName()); } catch (URISyntaxException e) { e.printStackTrace(); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status = null; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:com.jdom.ajatt.viewer.util.HtmlUtil.java
public static String getRequest(Activity activity, final String url) { SharedPreferences prefs = activity.getSharedPreferences(CLASS_NAME, Context.MODE_PRIVATE); String cachedUrlContents = prefs.getString(url, null); String urlRetrievalTimeKey = url + ".time"; long cachedUrlRetrievalTime = prefs.getLong(urlRetrievalTimeKey, 0L); long ageOfCachedData = System.currentTimeMillis() - cachedUrlRetrievalTime; if (cachedUrlRetrievalTime == 0) { Log.d(CLASS_NAME, "Did not find cached data for URL [" + url + "]."); } else {/*from w w w .j av a2s . c o m*/ Log.d(CLASS_NAME, "URL [" + url + "] has been cached for [" + ageOfCachedData + "] ms."); } Future<String> result = null; boolean expired = ageOfCachedData > CACHE_URL_MILLISECONDS; if (expired) { Log.d(CLASS_NAME, "URL [" + url + "] data is stale."); } else { long timeRemainingValidCache = CACHE_URL_MILLISECONDS - ageOfCachedData; Log.d(CLASS_NAME, "URL [" + url + "] data has [" + timeRemainingValidCache + "] ms of validity remaining."); } if (cachedUrlContents == null || expired) { Callable<String> callable = new Callable<String>() { public String call() throws Exception { long start = System.currentTimeMillis(); Log.d(CLASS_NAME, "Retrieving URL [" + url + "]."); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); return HttpHelper.request(response); } catch (Exception ex) { Log.e(CLASS_NAME, "Failure to retrieve the url!", ex); return null; } finally { Log.d(CLASS_NAME, "Retrieving URL [" + url + "] took [" + (System.currentTimeMillis() - start) + "] ms to retrieve."); } } }; ExecutorService executor = Executors.newSingleThreadExecutor(); result = executor.submit(callable); } if (cachedUrlContents == null) { try { cachedUrlContents = result.get(); Editor editor = prefs.edit(); editor.putLong(urlRetrievalTimeKey, System.currentTimeMillis()); editor.putString(url, cachedUrlContents); editor.commit(); } catch (Exception e) { Log.e(CLASS_NAME, "Failure to retrieve the url!", e); } } return cachedUrlContents; }
From source file:groovesquid.Grooveshark.java
public static String sendRequest(String method, HashMap<String, Object> parameters) { if (tokenExpires <= new Date().getTime() && tokenExpires != 0 && !"initiateSession".equals(method) && !"getCommunicationToken".equals(method) && !"getCountry".equals(method)) { try {//from w ww .j av a 2s .co m InitThread initThread = new InitThread(); initThread.start(); initThread.getLatch().await(); } catch (InterruptedException ex) { log.log(Level.SEVERE, null, ex); } } String responseContent = null; HttpEntity httpEntity = null; try { Client client = clients.getHtmlshark(); String protocol = "http://"; if (method.equals("getCommunicationToken")) { protocol = "https://"; } String url = protocol + "grooveshark.com/more.php?" + method; for (String jsqueueMethod : jsqueueMethods) { if (jsqueueMethod.equals(method)) { client = clients.getJsqueue(); break; } } header.put("client", client.getName()); header.put("clientRevision", client.getRevision()); header.put("privacy", "0"); header.put("uuid", uuid); header.put("country", country); if (!method.equals("initiateSession")) { header.put("session", session); header.put("token", generateToken(method, client.getSecret())); } Gson gson = new Gson(); String jsonString = gson.toJson(new JsonRequest(header, parameters, method)); log.info(">>> " + jsonString); HttpPost httpPost = new HttpPost(url); httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); httpPost.setHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); httpPost.setHeader("Referer", "http://grooveshark.com/JSQueue.swf?" + client.getRevision()); httpPost.setHeader("Content-Language", "en-US"); httpPost.setHeader("Cache-Control", "max-age=0"); httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.3"); httpPost.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch"); httpPost.setHeader("Origin", "http://grooveshark.com"); if (!method.equals("initiateSession")) { httpPost.setHeader("Cookie", "PHPSESSID=" + session); } httpPost.setEntity(new StringEntity(jsonString, "UTF-8")); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (Main.getConfig().getProxyHost() != null && Main.getConfig().getProxyPort() != null) { httpClientBuilder .setProxy(new HttpHost(Main.getConfig().getProxyHost(), Main.getConfig().getProxyPort())); } HttpClient httpClient = httpClientBuilder.build(); HttpResponse httpResponse = httpClient.execute(httpPost); ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity.writeTo(baos); } else { throw new RuntimeException("method " + method + ": " + statusLine); } responseContent = baos.toString("UTF-8"); } catch (Exception ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } finally { try { EntityUtils.consume(httpEntity); } catch (IOException ex) { Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex); } } log.info("<<< " + responseContent); return responseContent; }
From source file:minghai.nisesakura.SimpleBottleHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}./*ww w . j a v a2 s .c o m*/ * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized LinkedList<String> getUrlContent(String url) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } Log.d(TAG, "getUrlContent: url = " + url); // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", sUserAgent); try { HttpResponse response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "Shift_JIS")); while (true) { if (br.readLine().equals("")) break; } LinkedList<String> results = new LinkedList<String>(); for (String line = br.readLine(); line != null; line = br.readLine()) { String[] column = line.split("\t"); Log.d(TAG, "column[7] = " + column[7]); results.add(column[7]); } br.close(); // Return result from buffered stream return results; } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:org.vsepml.storm.sensapp.RestRequest.java
public static boolean isCompositeRegistred(Composite composite) { URI target = null;/*from w ww . j a v a 2s.co m*/ try { target = new URI(composite.getUri().toString() + COMPOSITE_PATH + "/" + composite.getName()); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status = null; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { e.printStackTrace(); } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:de.wdilab.coma.gui.extensions.RemoteRepo.java
public static boolean getRemoteConnection(String s, UUID uid) { UUID uuid;//w ww . ja va 2s . co m String xslt_text; boolean is_stored = false; xslt_text = s.replaceAll("\"", "\\\""); xslt_text = xslt_text.replaceAll("\'", "\\\'"); uuid = uid; try { File f = new File("helpingFile.csv"); PrintWriter output = new PrintWriter(new FileWriter(f)); output.println("uuid,data"); xslt_text.trim(); xslt_text = xslt_text.replace("\n", "").replace("\r", ""); output.println(uuid + "," + xslt_text); output.close(); HttpClient client = new DefaultHttpClient(); FileEntity entity = new FileEntity(f, ContentType.create("text/plain", "UTF-8")); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); HttpResponse response = client.execute(httppost); // System.out.println(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) is_stored = true; f.delete(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } // System.out.println("xslt stored "+is_stored); return is_stored; }
From source file:net.modelbased.proasense.storage.registry.RestRequest.java
public static boolean isSensorRegistered(Sensor sensor) { URI target = null;// w ww . jav a2 s . c o m try { target = new URI(sensor.getUri().toString() + SENSOR_PATH + "/" + sensor.getName()); } catch (URISyntaxException e) { e.printStackTrace(); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status = null; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:com.rylinaux.plugman.util.BukGetUtil.java
/** * Get the slug of the plugin./*from w w w . j a v a 2s .com*/ * * @param name the name of the plugin. * @return the slug of the plugin. */ public static String getPluginSlug(String name) { HttpClient client = HttpClients.createMinimal(); HttpGet get = new HttpGet(API_BASE_URL + "search/slug/like/" + name + "?fields=plugin_name,slug"); try { HttpResponse response = client.execute(get); String body = IOUtils.toString(response.getEntity().getContent()); JSONArray array = (JSONArray) JSONValue.parse(body); for (int i = 0; i < array.size(); i++) { JSONObject json = (JSONObject) array.get(i); String pluginName = (String) json.get("plugin_name"); if (name.equalsIgnoreCase(pluginName)) return (String) json.get("slug"); } } catch (IOException e) { } return null; }
From source file:net.modelbased.proasense.storage.registry.RestRequest.java
public static boolean isCompositeRegistered(Composite composite) { URI target = null;/*from w w w . jav a 2s. c o m*/ try { target = new URI(composite.getUri().toString() + COMPOSITE_PATH + "/" + composite.getName()); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status = null; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { e.printStackTrace(); } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:Main.java
/** * Performs an HTTP Post request to the specified url with the * specified parameters, and return the string from the HttpResponse. * * @param url The web address to post the request to * @param postParameters The parameters to send via the request * @return The result string of the request * @throws Exception//from w w w . j a v a2s . c o m */ public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception { BufferedReader in = null; try { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }