List of usage examples for org.apache.http.client HttpClient execute
HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;
From source file:com.book.jtm.chap03.HttpClientDemo.java
public static void sendGetRequest(String url) throws IOException { HttpClient httpclient = new DefaultHttpClient(defaultHttpParams()); HttpGet httpget = new HttpGet(url); // Header//from w ww .j a v a2s .c o m httpget.addHeader("Connection", "Keep-Alive"); HttpResponse response; response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); Log.e("", "### : " + result); instream.close(); } }
From source file:com.markwatson.linkeddata.DBpediaLookupClientJson.java
public static String lookup(String query) { StringBuffer sb = new StringBuffer(); try {/*from www . j av a2 s.com*/ HttpClient httpClient = new DefaultHttpClient(); String query2 = query.replaceAll(" ", "+"); HttpGet getRequest = new HttpGet( "http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString=" + query2); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) return "Server error"; BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String line; while ((line = br.readLine()) != null) { sb.append(line); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
From source file:de.yaio.commons.http.HttpUtils.java
/** * execute the prepared Request//from w w w.j a v a2s.com * @param request request to call * @param username username for auth * @param password password for auth * @return HttpResponse * @throws ClientProtocolException possible Exception if Request-state <200 > 299 * @throws IOException possible Exception if Request-state <200 > 299 */ public static HttpResponse executeRequest(final HttpUriRequest request, final String username, final String password) throws ClientProtocolException, IOException { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpResponse response = client.execute(request); return response; }
From source file:com.oliversride.wordryo.UpdateCheckReceiver.java
private static String runPost(HttpPost post, JSONObject params) { String result = null;//from www. j a v a 2 s. c om try { String jsonStr = params.toString(); List<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair(k_PARAMS, jsonStr)); post.setEntity(new UrlEncodedFormEntity(nvp)); // Execute HTTP Post Request HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (null != entity) { result = EntityUtils.toString(entity); if (0 == result.length()) { result = null; } } } catch (java.io.UnsupportedEncodingException uee) { DbgUtils.loge(uee); } catch (java.io.IOException ioe) { DbgUtils.loge(ioe); } return result; }
From source file:com.harshad.linconnectclient.NotificationUtilities.java
public static boolean sendData(Context c, Notification n, String packageName) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // Check Wifi state, whether notifications are enabled globally, and // whether notifications are enabled for specific application if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) { String ip = prefs.getString("pref_ip", "0.0.0.0:9090"); // Magically extract text from notification ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n); // Use PackageManager to get application name and icon final PackageManager pm = c.getPackageManager(); ApplicationInfo ai;/*w w w . j a va 2 s . c om*/ try { ai = pm.getApplicationInfo(packageName, 0); } catch (final NameNotFoundException e) { ai = null; } String notificationBody = ""; String notificationHeader = ""; // Create header and body of notification if (notificationData.size() > 0) { notificationHeader = notificationData.get(0); if (notificationData.size() > 1) { notificationBody = notificationData.get(1); } } else { return false; } for (int i = 2; i < notificationData.size(); i++) { notificationBody += "\n" + notificationData.get(i); } // Append application name to body if (pm.getApplicationLabel(ai) != null) { if (notificationBody.isEmpty()) { notificationBody = "via " + pm.getApplicationLabel(ai); } else { notificationBody += " (via " + pm.getApplicationLabel(ai) + ")"; } } // Setup HTTP request MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // If the notification contains an icon, use it if (n.largeIcon != null) { entity.addPart("notificon", new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png")); } // Otherwise, use the application's icon else { entity.addPart("notificon", new InputStreamBody( ImageUtilities.bitmapToInputStream( ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))), "drawable.png")); } HttpPost post = new HttpPost("http://" + ip + "/notif"); post.setEntity(entity); try { post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"), Base64.URL_SAFE | Base64.NO_WRAP)); post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"), Base64.URL_SAFE | Base64.NO_WRAP)); } catch (UnsupportedEncodingException e) { post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); } // Send HTTP request HttpClient client = new DefaultHttpClient(); HttpResponse response; try { response = client.execute(post); String html = EntityUtils.toString(response.getEntity()); if (html.contains("true")) { return true; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:com.websqrd.catbot.scraping.HttpHandler.java
public static String executeGet(String url, String encoding) { String resultString = ""; HttpClient httpclient = new DefaultHttpClient(); InputStream is = null;//from w w w . ja v a 2 s. c o m ByteArrayOutputStream baos = null; try { HttpGet httget = new HttpGet(url); HttpResponse response = httpclient.execute(httget); HttpEntity entity = response.getEntity(); Header header = entity.getContentType(); String type = header.getValue().toLowerCase(); baos = new ByteArrayOutputStream(); if (type.startsWith("text/html")) { byte[] buf = new byte[1024]; is = entity.getContent(); for (int rlen = 0; (rlen = is.read(buf, 0, buf.length)) > 0;) { baos.write(buf, 0, rlen); } resultString = new String(baos.toByteArray(), encoding); } } catch (Exception e) { logger.error("", e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (baos != null) try { baos.close(); } catch (IOException e) { } } return resultString; }
From source file:com.appdynamics.openstack.nova.RestClient.java
static String doDelete(String url, String token) throws Exception { HttpClient httpClient = httpClientWithTrustManager(); HttpDelete delete = new HttpDelete(url); delete.addHeader("accept", xmlContentType); delete.addHeader("X-Auth-Token", token); HttpResponse response = httpClient.execute(delete); return getResponseString(httpClient, response); }
From source file:org.openjena.riot.web.HttpOp.java
/** GET * <p>The acceptHeader string is any legal value for HTTP Accept: field. * <p>The handlers are the set of content types (without charset), * used to dispatch the response body for handling. * <p>A Map entry of ("*",....) is used "no handler found". * <p>HTTP responses 400 and 500 become exceptions. *//* www. java 2s . com*/ public static void execHttpGet(String url, String acceptHeader, Map<String, HttpResponseHandler> handlers) { try { long id = counter.incrementAndGet(); String requestURI = determineRequestURI(url); String baseIRI = determineBaseIRI(requestURI); HttpGet httpget = new HttpGet(requestURI); if (log.isDebugEnabled()) log.debug(format("[%d] %s %s", id, httpget.getMethod(), httpget.getURI().toString())); // Accept if (acceptHeader != null) httpget.addHeader(HttpNames.hAccept, acceptHeader); // Execute HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); // Handle response httpResponse(id, response, baseIRI, handlers); httpclient.getConnectionManager().shutdown(); } catch (IOException ex) { ex.printStackTrace(System.err); } }
From source file:com.arvos.arviewer.ArvosHttpRequest.java
private static InputStream openHttpGETConnection(String url) throws Exception { InputStream inputStream = null; HttpClient httpclient = new DefaultHttpClient(); HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); inputStream = httpResponse.getEntity().getContent(); return inputStream; }
From source file:grandroid.geo.Geocoder.java
public static double[] getLocationFromString(String address) throws JSONException { try {/*from w w w . j ava 2 s .c o m*/ HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + URLEncoder.encode(address, "UTF-8") + "&ka&sensor=false"); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); jsonObject = new JSONObject(stringBuilder.toString()); double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry") .getJSONObject("location").getDouble("lng"); double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry") .getJSONObject("location").getDouble("lat"); return new double[] { lat, lng }; } catch (UnsupportedEncodingException ex) { Log.e("grandroid", null, ex); return new double[] { 0, 0 }; } }