List of usage examples for org.apache.http.impl.client DefaultHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:parlare.application.server.controller.ControllerFunctions.java
public static String listCookies(String method, String listCookies) throws IOException { String printHTML = ""; switch (method) { case "javascript": printHTML += "<script>"; printHTML += "function setCookie(name,value,days) { "; printHTML += "var expires = \"\"; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = \"; expires=\" + date.toGMTString(); } "; printHTML += "document.cookie = name + \"=\" + value + expires + \"; path=/\";"; printHTML += "} "; printHTML += "function getCookie(name) { var nameEQ = name + \"=\"; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; "; printHTML += "while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } "; printHTML += "function eraseCookie(name) { setCookie(name, \"\", -1); } "; printHTML += "</script>"; if (listCookies != null) { String[] tokens = listCookies.split(";"); printHTML += "<script>"; for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { printHTML += " setCookie('" + data[0] + "', '" + data[1] + "', 60);"; }/*from www . ja va 2 s. c om*/ } printHTML += "</script>"; } break; case "java": DefaultHttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = httpClient.getCookieStore(); BasicClientCookie cookie = new BasicClientCookie("HelpMeUniverse", "I need your help my dear universe"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 100); cookie.setExpiryDate(calendar.getTime()); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); // Prepare a request object HttpGet httpGet = new HttpGet("http://localhost/"); // Execute the request HttpResponse httpResponse = httpClient.execute(httpGet); // Examine the response status System.out.println("Http request response is: " + httpResponse.getStatusLine()); break; } return printHTML; }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
protected static HttpResponse doPost(HttpPost post) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); post.setHeader(AUTH_HEADER);/*from www . j av a 2s .c om*/ return client.execute(post); }
From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java
public static boolean deleteOAuthApplication(String user, String appName, String clientid, String host) throws DynamicClientRegistrationException { if (log.isDebugEnabled()) { log.debug("Invoking DCR service to remove OAuth application created for web app : " + appName); }//from w w w . java 2 s .c om DefaultHttpClient httpClient = getHTTPSClient(); try { URI uri = new URIBuilder().setScheme( DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL) .setHost(host) .setPath( DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) .setParameter("applicationName", appName).setParameter("userId", user) .setParameter("consumerKey", clientid).build(); HttpDelete httpDelete = new HttpDelete(uri); HttpResponse response = httpClient.execute(httpDelete); int status = response.getStatusLine().getStatusCode(); if (status == 200) { return true; } } catch (IOException e) { throw new DynamicClientRegistrationException( "Connection error occurred while constructing the payload for " + "invoking DCR endpoint for unregistering the web-app : " + appName, e); } catch (URISyntaxException e) { throw new DynamicClientRegistrationException( "Exception occurred while constructing the URI for invoking " + "DCR endpoint for unregistering the web-app : " + appName, e); } finally { if (httpClient != null) { httpClient.close(); } } return false; }
From source file:imageLines.ImageHelpers.java
public static Boolean checkImageHeader(String imageURLString, String uname, String pass) throws ClientProtocolException { /*/*from ww w . j a va 2 s. com*/ URLConnection conn=imageURL.openConnection(); String userPassword=user+":"+ pass; String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); conn.setRequestProperty ("Authorization", "Basic " + encoding);*/ DefaultHttpClient httpclient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(uname, pass)); HttpHead head = new HttpHead(imageURLString); //HttpGet httpget = new HttpGet(imageURLString); System.out.println("executing head request" + head.getRequestLine()); HttpResponse response; try { response = httpclient.execute(head); int code = response.getStatusLine().getStatusCode(); if (code == 200 || code == 304) return true; } catch (IOException ex) { Logger.getLogger(ImageHelpers.class.getName()).log(Level.SEVERE, null, ex); } return false; }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
protected static HttpResponse execute(HttpUriRequest request) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); request.setHeader(AUTH_HEADER);/*from ww w.ja va 2 s . c o m*/ return client.execute(request); }
From source file:com.dajodi.scandic.ScandicSessionHelper.java
public static MemberInfo fetchInfo(String username, String password) throws Exception { DefaultHttpClient client = Singleton.INSTANCE.getHttpClient(); if (!isLoggedIn()) { // clear the cookies just to be safe client.getCookieStore().clear(); login(username, password);/* w w w . j a v a2 s .co m*/ } URI uri = new URI("https://www.scandichotels.com/Frequent-Guest-Programme/"); HttpGet get = new HttpGet(uri); Util.gzipify(get); // no redirect please final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); get.setParams(params); HttpResponse response = client.execute(get); response = checkSessionStillValid(uri, get, response, username, password); if (response.getStatusLine().getStatusCode() != 200) { throw new ScandicHtmlException("Non-200 response returned for frequent guest page"); } InputStream instream = Util.ungzip(response); // should we try to minimize the input stream? // instream = minimizeFormInput(instream, ACCOUNT_DIV_START, ACCOUNT_DIV_END); try { long before = System.currentTimeMillis(); MemberInfo memberInfo = Singleton.INSTANCE.getScraper().scrapeMemberInfo(instream); Log.d("Scrape member info took " + (System.currentTimeMillis() - before) + "ms"); return memberInfo; } finally { instream.close(); } }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static InputStream getResponseContentStream(DefaultHttpClient client, HttpUriRequest request, String message) throws XtentisException { if (null == request) { throw new IllegalArgumentException("null request"); //$NON-NLS-1$ }/*from ww w . jav a 2 s. c o m*/ HttpResponse response = null; try { response = client.execute(request); HttpEntity content = response.getEntity(); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { if (null != message) { throw new XtentisException(String.format(message, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } return content.getContent(); } catch (XtentisException ex) { closeResponse(response); throw ex; } catch (Exception e) { log.error(e.getMessage(), e); request.abort(); closeResponse(response); throw new XtentisException(e.getMessage(), e); } }
From source file:it.restrung.rest.client.DefaultRestClientImpl.java
/** * Performs a PUT request to the given url * * @param url the url/*from www . j a va 2s .co m*/ * @param user an optional user for basic auth * @param password an optional password for basic auth * @param body an optional body to send with the request * @param timeout the request timeout * @param delegate the api delegate that will receive callbacks regarding progress and results * @return the response body as a string * @throws APIException */ public static String performPut(String url, String user, String password, String body, int timeout, APIDelegate<?> delegate) throws APIException { Log.d(RestClient.class.getSimpleName(), "PUT: " + url); String responseBody; try { DefaultHttpClient httpclient = HttpClientFactory.getClient(); HttpPut httpPut = new HttpPut(url); setupTimeout(timeout, httpclient); setupCommonHeaders(httpPut); setupBasicAuth(user, password, httpPut); setupRequestBody(httpPut, body, null, null); handleRequest(httpPut, delegate); HttpResponse response = httpclient.execute(httpPut); responseBody = handleResponse(response, delegate); } catch (ClientProtocolException e) { throw new APIException(e, APIException.UNTRACKED_ERROR); } catch (IOException e) { throw new APIException(e, APIException.UNTRACKED_ERROR); } return responseBody; }
From source file:com.android.feedmeandroid.HTTPClient.java
public static ArrayList<JSONObject> SendHttpPost(String URL, JSONObject jsonObjSend) { try {// w ww . j ava2 s .c o m ArrayList<JSONObject> retArray = new ArrayList<JSONObject>(); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accepts", "application/json"); httpPostRequest.setHeader("Content-Type", "application/json"); // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set // this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.v(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); Log.i(TAG, resultString); instream.close(); resultString = resultString.substring(1, resultString.length() - 2); // remove wrapping "[" and // "]" String[] results = resultString.split("\\},\\{"); for (int i = 0; i < results.length; i++) { JSONObject jsonObjRecv; String res = results[i]; // Transform the String into a JSONObject if (i == 0 && results.length > 1) { jsonObjRecv = new JSONObject(res + "}"); } else if (i == results.length - 1 && results.length > 1) { jsonObjRecv = new JSONObject("{" + res); } else { jsonObjRecv = new JSONObject("{" + res + "}"); } retArray.add(jsonObjRecv); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); } return retArray; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:com.dajodi.scandic.ScandicSessionHelper.java
private static HttpResponse checkSessionStillValid(URI uri, HttpGet get, HttpResponse response, String username, String password) throws Exception { DefaultHttpClient client = Singleton.INSTANCE.getHttpClient(); if (response.getStatusLine().getStatusCode() == 302 && response.getFirstHeader("Location").getValue().toLowerCase().contains("sessionexpired")) { // session seems to have expired... get.abort();//from w ww . j a v a 2 s .c o m Log.d("Session seems to have expired, clearing cookies, relogging in"); client.getCookieStore().clear(); login(username, password); Log.d("Trying to get secure page again"); get = new HttpGet(uri); Util.gzipify(get); response = client.execute(get); } // check the headers, we can assume a few exist for cached requests (save issuing a request for 300k) else if (!containsNoCacheHeaders(response)) { get.abort(); Log.d("Session seems to have been hijacked, clearing cookies, relogging in"); client.getCookieStore().clear(); login(username, password); Log.d("Trying to get secure page again"); get = new HttpGet(uri); Util.gzipify(get); response = client.execute(get); } return response; }