protected GetMethod createRequest(String downloadUrl, Map<String, String> headers) { GetMethod request = new GetMethod(downloadUrl); request.setFollowRedirects(true); if (MapUtils.isNotEmpty(headers)) { for (String key : headers.keySet()) { request.setRequestHeader(key, headers.get(key)); reqHeaders.put(key, headers.get(key)); } } return request; }
@Override public HTTPResponse get(final URL url) throws IOException { GetMethod getMethod = new GetMethod(url.toExternalForm()); getMethod.setDoAuthentication(user != null && password != null); if (tryGzip) { getMethod.setRequestHeader("Accept-Encoding", "gzip"); } int responseCode = executeMethod(getMethod); if (200 != responseCode) { getMethod.releaseConnection(); throw new IOException( "Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm()); } return new HttpMethodResponse(getMethod); }
getMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE); getMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials);
// Obtain SID GetMethod getLogin = new GetMethod("https://www.google.com/accounts/ClientLogin?service=reader&Email="+ login+"&Passwd="+password); client.executeMethod(getLogin); String loginText = getLogin.getResponseBodyAsString(); // The value of SID is loginText.substring (4,firstLineLength) BufferedReader reader = new BufferedReader(new StringReader(loginText)); String SID = loginText.substring(4, reader.readLine().length() ); GetMethod grabData = new GetMethod("http://www.google.com/reader/atom/user/-/state/com.google/broadcast"); grabData.setRequestHeader("Cookie", "SID="+SID); client.executeMethod(grabData);
private static <T> T getResponse(HttpClient http, String requestUrl, Class<T> clazz) { GetMethod request = new GetMethod(requestUrl); int code; try { request.setDoAuthentication(true); request.setRequestHeader("Accept", "application/xml"); code = http.executeMethod(request); if (code == 200) { InputStream res = request.getResponseBodyAsStream(); JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); InputStreamReader reader = new InputStreamReader(res); return clazz.cast(unmarshaller.unmarshal(reader)); } } catch (Exception e) { throw new RuntimeException(e); } finally { request.releaseConnection(); } throw new RuntimeException("Accessing the URL " + requestUrl + " failed with code " + code); }
private static InetAddress ifConfigLookup() { final HttpClient client = new HttpClient(); final GetMethod get = new GetMethod("http://ifconfig.me"); // The service returns just the IP if we pretend we're curl. get.setRequestHeader("User-Agent", "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3"); get.setFollowRedirects(true); try { final int response = client.executeMethod(get); if (response < 200 || response > 299) { LOG.warn("Got non-200 level response: "+response); return null; } final String body = new String(get.getResponseBody(), "UTF-8"); LOG.info("Got response body:\n{}", body); return InetAddress.getByName(body.trim()); } catch (final HttpException e) { LOG.warn("HTTP error?", e); } catch (final IOException e) { LOG.warn("Error connecting?", e); } catch (final Exception e) { LOG.warn("Some other error?", e); } finally { get.releaseConnection(); } return null; }
public static String getReaderContent(String accessToken){ String url = "https://www.google.com/reader/api/0/subscription/list" ; HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); String response=""; method.setRequestHeader("Authorization", "OAuth "+accessToken); try { int statusCode = client.executeMethod(method); String response= method.getResponseBodyAsString(); System.out.println("response " + responseStr); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; }
/** * Builds the HTTP GET method used to fetch the metadata. The returned method advertises support for GZIP and * deflate compression, enables conditional GETs if the cached metadata came with either an ETag or Last-Modified * information, and sets up basic authentication if such is configured. * * @return the constructed GET method */ protected GetMethod buildGetMethod() { GetMethod getMethod = new GetMethod(getMetadataURI()); getMethod.addRequestHeader("Connection", "close"); getMethod.setRequestHeader("Accept-Encoding", "gzip,deflate"); if (cachedMetadataETag != null) { getMethod.setRequestHeader("If-None-Match", cachedMetadataETag); } if (cachedMetadataLastModified != null) { getMethod.setRequestHeader("If-Modified-Since", cachedMetadataLastModified); } if (httpClient.getState().getCredentials(authScope) != null) { log.debug("Using BASIC authentication when retrieving metadata from '{}", metadataURI); getMethod.setDoAuthentication(true); } return getMethod; }
private GetMethod execDiffMethod(ReviewboardConnection con, HttpClient http, String url) throws IOException { ensureAuthentication(con, http); String diffUrl = con.buildApiUrl(url, "diffs"); Response d = getResponse(http, diffUrl, Response.class); if (d.count < 1) throw new RuntimeException("Review " + url + " has no diffs"); // String diffUrl = url.concat("diff/raw/"); GetMethod diff = new GetMethod(diffUrl + d.count + "/"); diff.setDoAuthentication(true); diff.setRequestHeader("Accept", "text/x-patch"); http.executeMethod(diff); return diff; }
/** Retrieve a document from the given URL using HTTP GET * * @param url * @return Document as stream * @throws HttpException * @throws IOException * @see org.apache.commons.httpclient.methods.GetMethod */ public static InputStream getDocumentAsInputStream(String url, List<String> mimetypes) throws HttpException, IOException { StringBuilder accept = new StringBuilder(); if (mimetypes != null) { for (String mimetype : mimetypes) { if (accept.length() > 0) { accept.append(","); } accept.append(mimetype); } } //Execute a GET method on the URL GetMethod get = new GetMethod(url); get.setFollowRedirects(true); if (accept.length() > 0) { get.setRequestHeader("Accept", accept.toString()); } get.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 4.0)"); _httpClient.executeMethod(get); return get.getResponseBodyAsStream(); }
@Override public HTTPResponse get(final URL url) throws IOException { GetMethod getMethod = new GetMethod(url.toExternalForm()); getMethod.setDoAuthentication(user != null && password != null); if (tryGzip) { getMethod.setRequestHeader("Accept-Encoding", "gzip"); } int responseCode = executeMethod(getMethod); if (200 != responseCode) { getMethod.releaseConnection(); throw new IOException( "Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm()); } return new HttpMethodResponse(getMethod); }
/** * Factory method to create a {@link GetMethod} object. * * @param uri URI * @return a {@link GetMethod} instance */ private GetMethod createGetMethod( final String uri ) { final GetMethod method = new GetMethod( uri ); // add all parameters as headers for ( final Iterator i = this.m_parameters.keySet().iterator(); i.hasNext(); ) { final String key = (String) i.next(); final String value = (String) this.m_parameters.get( key ); if ( this.getLogger().isDebugEnabled() ) { this.getLogger().debug( "Adding header '" + key + "', with value '" + value + "'" ); } method.setRequestHeader( key, value ); } return method; }
private GetMethod doGet(URL url, int timeout) throws IOException { HttpClient client = getClient(); client.setTimeout(timeout); GetMethod get = new GetMethod(normalizeToString(url)); get.setDoAuthentication(useAuthentication(url) || useProxyAuthentication()); get.setRequestHeader("Accept-Encoding", "gzip,deflate"); client.executeMethod(get); return get; }
try { HttpClient client = new HttpClient( new MultiThreadedHttpConnectionManager()); client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials("username", "password"); client.getState().setCredentials(AuthScope.ANY, credentials); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); GetMethod getMethod = new GetMethod("your_url"); getMethod.setRequestHeader("Accept", "application/xml"); client.executeMethod(getMethod); int status = getMethod.getStatusCode(); getMethod.setDoAuthentication(true); System.out.println("status: " + status); if (status == HttpStatus.SC_OK) { String responseBody = getMethod.getResponseBodyAsString(); String resp = responseBody.replaceAll("\n", " "); System.out.println("RESPONSE \n" + resp); } } catch (Exception e) { e.printStackTrace(); }
@Override protected String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException { String freebusyUrl = publicFolderUrl + "/?cmd=freebusy" + "&start=" + start + "&end=" + end + "&interval=" + interval + "&u=SMTP:" + attendee; GetMethod getMethod = new GetMethod(freebusyUrl); getMethod.setRequestHeader("Content-Type", "text/xml"); String fbdata = null; try { DavGatewayHttpClientFacade.executeGetMethod(httpClient, getMethod, true); fbdata = StringUtil.getLastToken(getMethod.getResponseBodyAsString(), "<a:fbdata>", "</a:fbdata>"); } finally { getMethod.releaseConnection(); } return fbdata; }
public static String accessResource_Appache_commons(String url){ String response_String = null; HttpClient client = new HttpClient(); GetMethod method = new GetMethod( url ); // PostMethod method = new PostMethod( url ); method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); method.setQueryString(new NameValuePair[] { new NameValuePair("param1","value1"), new NameValuePair("param2","value2") }); //The pairs are encoded as UTF-8 characters. try{ int statusCode = client.executeMethod(method); System.out.println("Status Code = "+statusCode); //Get data as a String OR BYTE array method.getResponseBody() response_String = method.getResponseBodyAsString(); method.releaseConnection(); } catch(IOException e) { e.printStackTrace(); } return response_String; }
/** * {@inheritDoc} */ @Override public <MODEL extends Model> ConnectorResponse execute(Query<MODEL> query) { GetMethod method = null; String url = null; try { url = server.getHost() + URIUtil.encodeQuery(query.getUrl()); method = new GetMethod(url); method.setRequestHeader("Accept", query.getAcceptHeader()); httpClient.executeMethod(method); return getConnectorResponseFromMethod(method); } catch (HttpException e) { log.error("Failed to execute the query: " + query.getUrl(), e); } catch (IOException e) { } finally { if (method != null) { method.releaseConnection(); } } return null; }
private JSONObject pollForServerStatus() throws IOException, JSONException { JSONObject result = null; RackspaceRestClient client = env.fetchContext().client; String uri = "https://" + client.encodePath(region) + ".servers.api.rackspacecloud.com/v2/" + client.encodePath(client.getTenantID()) + "/servers/" + client.encodePath(id); GetMethod method = new GetMethod(uri); method.setRequestHeader("X-Auth-Token", client.getAuthToken()); method.setRequestHeader("Content-Type", "application/json"); int status = client.invokeMethod(method); String body = client.getBody(method); method.releaseConnection(); if (200 <= status && status <= 204) { JSONObject serverJSON = new JSONObject(body).getJSONObject("server"); result = serverJSON; } else { log.warn("Exception when polling server for status."); throw new IOException(String.format("%d %s %s", status, HttpStatus.getStatusText(status), body)); } return result; }
private JSONObject pollForDatabaseStatus() throws IOException, JSONException { JSONObject result = null; RackspaceRestClient client = env.fetchContext().client; String uri = "https://" + client.encodePath(region) + ".databases.api.rackspacecloud.com/v1.0/" + client.encodePath(client.getTenantID()) + "/instances/" + client.encodePath(id); GetMethod method = new GetMethod(uri); method.setRequestHeader("X-Auth-Token", client.getAuthToken()); method.setRequestHeader("Content-Type", "application/json"); int status = client.invokeMethod(method); String body = client.getBody(method); method.releaseConnection(); if (200 <= status && status <= 204) { JSONObject serverJSON = new JSONObject(body).getJSONObject("instance"); result = serverJSON; } else { log.warn("Exception when polling database for status."); throw new IOException(String.format("%d %s %s", status, HttpStatus.getStatusText(status), body)); } return result; }
get.setRequestHeader("Accept", "application/json"); try { int statusCode = client.executeMethod(get);