List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:org.sensapp.android.sensappdroid.restrequests.RestRequest.java
public static boolean isSensorRegistered(Sensor sensor) throws RequestErrorException { URI target;/*from www.j a va2 s . c o m*/ try { target = new URI(sensor.getUri().toString() + SENSOR_PATH + "/" + sensor.getName()); } catch (URISyntaxException e) { e.printStackTrace(); throw new RequestErrorException(e.getMessage()); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { throw new RequestErrorException(e.getMessage()); } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:org.sensapp.android.sensappdroid.restrequests.RestRequest.java
public static boolean isCompositeRegistered(Composite composite) throws RequestErrorException { URI target;//from www .j a v a 2 s .co m try { target = new URI(composite.getUri().toString() + COMPOSITE_PATH + "/" + composite.getName()); } catch (URISyntaxException e1) { e1.printStackTrace(); throw new RequestErrorException(e1.getMessage()); } HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(target); StatusLine status; try { status = client.execute(request).getStatusLine(); } catch (Exception e) { throw new RequestErrorException(e.getMessage()); } if (status.getStatusCode() == 200) { return true; } return false; }
From source file:com.teleca.jamendo.util.Caller.java
/** * Performs HTTP GET using Apache HTTP Client v 4 * /*from w ww . j a v a 2 s . co m*/ * @param url * @return * @throws ErrorMsg */ public static String doGet(String url) throws ErrorMsg { String data = null; if (requestCache != null) { data = requestCache.get(url); if (data != null) { Log.d(MyApplication.TAG, "Caller.doGet [cached] " + url); return data; } } // initialize HTTP GET request objects HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse; try { // execute request try { httpResponse = httpClient.execute(httpGet); } catch (UnknownHostException e) { ErrorMsg wsError = new ErrorMsg(); wsError.setMessage(e.getLocalizedMessage()); throw wsError; } catch (SocketException e) { ErrorMsg wsError = new ErrorMsg(); wsError.setMessage(e.getLocalizedMessage()); throw wsError; } // request data HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream inputStream = httpEntity.getContent(); data = convertStreamToString(inputStream); // cache the result if (requestCache != null) { requestCache.put(url, data); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d(MyApplication.TAG, "Caller.doGet " + url); return data; }
From source file:eg.nileu.cis.nilestore.main.HttpDealer.java
/** * Gets the.//ww w . j av a 2s. com * * @param url * the url * @param cap * the cap * @param downloadDir * the download dir * @throws ClientProtocolException * the client protocol exception * @throws IOException * Signals that an I/O exception has occurred. */ public static void get(String url, String cap, String downloadDir) throws ClientProtocolException, IOException { url = url + (url.endsWith("/") ? "" : "/") + "download/" + cap; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); if (response != null) { System.err.println(response.getStatusLine()); HttpEntity ht = response.getEntity(); final double filesize = ht.getContentLength(); FileOutputStream out = new FileOutputStream(FileUtils.JoinPath(downloadDir, cap)); OutputStreamProgress cout = new OutputStreamProgress(out, new ProgressListener() { @Override public void transfered(long bytes, float rate) { int percent = (int) ((bytes / filesize) * 100); String bar = ProgressUtils.progressBar("Download Progress: ", percent, rate); System.out.print("\r" + bar); } }); ht.writeTo(cout); out.close(); System.out.println(); } else { System.err.println("Error: response = null"); } client.getConnectionManager().shutdown(); }
From source file:com.gadelkareem.serverload.ServerLoadConfig.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 * // w ww . j a v a 2 s.com * @param url The exact URL to request. * @return The raw content returned by the server. */ protected static synchronized String getUrlContent(String url) { byte[] sBuffer = new byte[512]; // Create client and set our specific user-agent string HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); Log.d(TAG, "opening : " + url); try { HttpResponse response = client.execute(request); // Log.d( TAG, "getting status : " + url ); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { Log.d(TAG, "Invalid response from server: " + status.toString()); return ""; } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (Exception e) { Log.d(TAG, "Problem communicating with API : " + e); return ""; } }
From source file:org.wso2.dss.integration.test.odata.ODataSuperTenantUserTestCase.java
private static int sendDELETE(String endpoint, String acceptType) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpDelete httpDelete = new HttpDelete(endpoint); httpDelete.setHeader("Accept", acceptType); HttpResponse httpResponse = httpClient.execute(httpDelete); return httpResponse.getStatusLine().getStatusCode(); }
From source file:CB_Core.Api.PocketQuery.java
/** * @param AccessToken// ww w . j a va 2 s.c o m * Config.GetAccessToken(true) * @param pocketQueryConfig * Config.settings.PocketQueryFolder.getValue() * @param PqFolder * @return */ public static int DownloadSinglePocketQuery(PQ pocketQuery, String PqFolder) { HttpGet httpGet = new HttpGet( GroundspeakAPI.GS_LIVE_URL + "GetPocketQueryZippedFile?format=json&AccessToken=" + GroundspeakAPI.GetAccessToken(true) + "&PocketQueryGuid=" + pocketQuery.GUID); try { // String result = GroundspeakAPI.Execute(httpGet); httpGet.setHeader("Accept", "application/json"); httpGet.setHeader("Content-type", "application/json"); // Execute HTTP Post Request String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpGet); int buffLen = 32 * 1024; byte[] buff = new byte[buffLen]; InputStream inputStream = response.getEntity().getContent(); int buffCount = inputStream.read(buff, 0, buffLen); int buffPos = 0; result = ""; // now read from the response until the ZIP Informations are beginning or to the end of stream for (int i = 0; i < buffCount; i++) { byte c = buff[i]; result += (char) c; if (result.contains("\"ZippedFile\":\"")) { // The stream position represents the beginning of the ZIP block // to have a correct JSON Array we must add a "}} to the // result result += "\"}}"; buffPos = i; // Position im Buffer, an der die ZIP-Infos beginnen break; } } // try // Parse JSON Result { JSONTokener tokener = new JSONTokener(result); JSONObject json = (JSONObject) tokener.nextValue(); JSONObject status = json.getJSONObject("Status"); if (status.getInt("StatusCode") == 0) { GroundspeakAPI.LastAPIError = ""; SimpleDateFormat postFormater = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = postFormater.format(pocketQuery.DateLastGenerated); String local = PqFolder + "/" + pocketQuery.Name + "_" + dateString + ".zip"; // String test = json.getString("ZippedFile"); FileOutputStream fs; fs = new FileOutputStream(local); BufferedOutputStream bfs = new BufferedOutputStream(fs); try { // int firstZipPos = result.indexOf("\"ZippedFile\":\"") + 14; // int lastZipPos = result.indexOf("\"", firstZipPos + 1) - 1; CB_Utils.Converter.Base64.decodeStreamToStream(inputStream, buff, buffLen, buffCount, buffPos, bfs); } catch (Exception ex) { } // fs.write(resultByte); bfs.flush(); bfs.close(); fs.close(); result = null; System.gc(); return 0; } else { GroundspeakAPI.LastAPIError = ""; GroundspeakAPI.LastAPIError = "StatusCode = " + status.getInt("StatusCode") + "\n"; GroundspeakAPI.LastAPIError += status.getString("StatusMessage") + "\n"; GroundspeakAPI.LastAPIError += status.getString("ExceptionDetails"); return (-1); } } catch (JSONException e) { e.printStackTrace(); } } catch (ClientProtocolException e) { System.out.println(e.getMessage()); return (-1); } catch (IOException e) { System.out.println(e.getMessage()); return (-1); } return 0; }
From source file:com.byteridge.bookcircle.utils.ResponseParser.java
public static User GetUserDetails(String userId) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("user/show/" + userId + ".xml"); builder.appendQueryParameter("key", _ConsumerKey); HttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(builder.build().toString()); if (get_IsAuthenticated()) { _Consumer.sign(getRequest); }// w w w .j a va 2 s . c o m HttpResponse response; response = httpClient.execute(getRequest); Response responseData = ResponseParser.parse(response.getEntity().getContent()); return responseData.get_User(); }
From source file:og.android.tether.system.WebserviceTask.java
public static boolean downloadFile(String url, String destinationDirectory, String destinationFilename) { boolean filedownloaded = true; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(String.format(url)); Message msg = Message.obtain();//from w ww . j a va 2s . c o m try { HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); Log.d(MSG_TAG, "Request returned status " + status); if (status.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); int fileSize = (int) entity.getContentLength(); FileOutputStream out = new FileOutputStream( new File(destinationDirectory + "/" + destinationFilename)); byte buf[] = new byte[8192]; int len; int totalRead = 0; while ((len = instream.read(buf)) > 0) { msg = Message.obtain(); msg.what = MainActivity.MESSAGE_DOWNLOAD_PROGRESS; totalRead += len; msg.arg1 = totalRead / 1024; msg.arg2 = fileSize / 1024; MainActivity.currentInstance.viewUpdateHandler.sendMessage(msg); out.write(buf, 0, len); } out.close(); } else { throw new IOException(); } } catch (IOException e) { Log.d(MSG_TAG, "Can't download file '" + url + "' to '" + destinationDirectory + "/" + destinationFilename + "'."); filedownloaded = false; } msg = Message.obtain(); msg.what = MainActivity.MESSAGE_DOWNLOAD_COMPLETE; MainActivity.currentInstance.viewUpdateHandler.sendMessage(msg); return filedownloaded; }
From source file:org.wso2.dss.integration.test.odata.ODataSuperTenantUserTestCase.java
private static Object[] sendGET(String endpoint, String acceptType) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(endpoint); httpGet.setHeader("Accept", acceptType); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getEntity() != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;/* w w w.ja v a 2s. c o m*/ StringBuilder response = new StringBuilder(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() }; } else { return new Object[] { httpResponse.getStatusLine().getStatusCode() }; } }