Java Code Examples for org.apache.commons.httpclient.methods.GetMethod#getResponseHeader()

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod#getResponseHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VmRuntimeJettyKitchenSinkTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAsyncRequests_WaitUntilDone() throws Exception {
  long sleepTime = 2000;
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
  GetMethod get = new GetMethod(createUrl("/sleep").toString());
  get.addRequestHeader("Use-Async-Sleep-Api", "true");
  get.addRequestHeader("Sleep-Time", Long.toString(sleepTime));
  long startTime = System.currentTimeMillis();
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  Header vmApiWaitTime = get.getResponseHeader(VmRuntimeUtils.ASYNC_API_WAIT_HEADER);
  assertNotNull(vmApiWaitTime);
  assertTrue(Integer.parseInt(vmApiWaitTime.getValue()) > 0);
  long elapsed = System.currentTimeMillis() - startTime;
  assertTrue(elapsed >= sleepTime);
}
 
Example 2
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAuth_UserRequiredNoUser() throws Exception {
  String loginUrl = "http://login-url?url=http://test-app.googleapp.com/user/test-auth";
  CreateLoginURLResponse loginUrlResponse = new CreateLoginURLResponse();
  loginUrlResponse.setLoginUrl(loginUrl);
  // Fake the expected call to "user/CreateLoginUrl".
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  fakeApiProxy.addApiResponse(loginUrlResponse);

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/user/test-auth").toString());
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(302, httpCode);
  Header redirUrl = get.getResponseHeader("Location");
  assertEquals(loginUrl, redirUrl.getValue());
}
 
Example 3
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
public void testAuth_AdminRequiredNoUser() throws Exception {
  String loginUrl = "http://login-url?url=http://test-app.googleapp.com/user/test-auth";
  CreateLoginURLResponse loginUrlResponse = new CreateLoginURLResponse();
  loginUrlResponse.setLoginUrl(loginUrl);
  // Fake the expected call to "user/CreateLoginUrl".
  FakeableVmApiProxyDelegate fakeApiProxy = new FakeableVmApiProxyDelegate();
  ApiProxy.setDelegate(fakeApiProxy);
  fakeApiProxy.addApiResponse(loginUrlResponse);

  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/admin/test-auth").toString());
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(302, httpCode);
  Header redirUrl = get.getResponseHeader("Location");
  assertEquals(loginUrl, redirUrl.getValue());
}
 
Example 4
Source File: AbstractSolrAdminHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes an action or a command in SOLR using REST API 
 * 
 * @param httpClient HTTP Client to be used for the invocation
 * @param url Complete URL of SOLR REST API Endpoint
 * @return A JSON Object including SOLR response
 * @throws UnsupportedEncodingException
 */
protected JSONObject getOperation(HttpClient httpClient, String url) throws UnsupportedEncodingException 
{

    GetMethod get = new GetMethod(url);
    
    try {
        
        httpClient.executeMethod(get);
        if(get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                get.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(get);
            }
        }
        if (get.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + get.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()));
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
        
    }
    catch (IOException | JSONException e) 
    {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } 
    finally 
    {
        get.releaseConnection();
    }
}
 
Example 5
Source File: HTTPMetadataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Records the ETag and Last-Modified headers, from the response, if they are present.
 * 
 * @param getMethod GetMethod containing a valid HTTP response
 */
protected void processConditionalRetrievalHeaders(GetMethod getMethod) {
    Header httpHeader = getMethod.getResponseHeader("ETag");
    if (httpHeader != null) {
        cachedMetadataETag = httpHeader.getValue();
    }

    httpHeader = getMethod.getResponseHeader("Last-Modified");
    if (httpHeader != null) {
        cachedMetadataLastModified = httpHeader.getValue();
    }
}
 
Example 6
Source File: HttpClientUtil.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
public String getHeader(String url, String cookies, String headername) throws IOException {
//        clearCookies();
        GetMethod g = new GetMethod(url);
        g.setFollowRedirects(false);
        if (StringUtils.isNotEmpty(cookies)) {
            g.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(g);
        return g.getResponseHeader(headername) == null ? null : g.getResponseHeader(headername).getValue();
    }
 
Example 7
Source File: HttpClientUtil.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
public String getHeader(String url, String cookies, String headername) throws IOException {
//        clearCookies();
        GetMethod g = new GetMethod(url);
        g.setFollowRedirects(false);
        if (StringUtils.isNotEmpty(cookies)) {
            g.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(g);
        return g.getResponseHeader(headername) == null ? null : g.getResponseHeader(headername).getValue();
    }
 
Example 8
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public String loginWithToken(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    final Header securityToken = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN);
    assertTrue(securityToken != null && StringHelper.containsNonWhitespace(securityToken.getValue()));
    return securityToken == null ? null : securityToken.getValue();
}
 
Example 9
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public String loginWithToken(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    final Header securityToken = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN);
    assertTrue(securityToken != null && StringHelper.containsNonWhitespace(securityToken.getValue()));
    return securityToken == null ? null : securityToken.getValue();
}
 
Example 10
Source File: BaseHttp.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
/**
 * 模拟get
 *
 * @param args
 * @param retry
 *            重试第几次了
 * @return
 * @throws HttpException
 */
private static String doGet(HashMap<String, Object> args, int retry) throws HttpException {
    int maxRedirect = (Integer) args.get("maxRedirect");
    String result = null;
    if (retry > maxRedirect) {
        return result;
    }
    String url = (String) args.get("url");
    HashMap<String, String> header = (HashMap<String, String>) args.get("header");
    BaseCookie[] cookie = (BaseCookie[]) args.get("cookie");
    String charset = (String) args.get("charset");
    Integer timeout = (Integer) args.get("timeout");
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    BaseHttp.init(client, method, header, cookie, charset, timeout);
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            result = getResponse(method, charset);
        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER
                || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            // 301, 302, 303, 307 跳转
            Header locationHeader = method.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                retry++;
                args.put("url", location);
                result = BaseHttp.doGet(args, retry);
            }
        }
    } catch (IOException e) {
        throw new HttpException("执行HTTP Get请求" + url + "时,发生异常! => " + e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return result;
}
 
Example 11
Source File: MailingComponentImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public boolean loadContentFromURL() {
	boolean returnValue = true;

	// return false;

	if ((type != TYPE_IMAGE) && (type != TYPE_ATTACHMENT)) {
		return false;
	}
	
	HttpClient httpClient = new HttpClient();
	String encodedURI = encodeURI(componentName);
	GetMethod get = new GetMethod(encodedURI);
	get.setFollowRedirects(true);
	
	try {
		NetworkUtil.setHttpClientProxyFromSystem(httpClient, encodedURI);
		
		httpClient.getParams().setParameter("http.connection.timeout", 5000);

		if (httpClient.executeMethod(get) == 200) {
			get.getResponseHeaders();
			
			// TODO: Due to data types of DB columns binblock and emmblock, replacing getResponseBody() cannot be replaced by safer getResponseBodyAsStream(). Better solutions?
			Header contentType = get.getResponseHeader("Content-Type");
			String contentTypeValue = "";
			if(contentType != null) {
				contentTypeValue = contentType.getValue();
			} else {
				logger.debug("No content-type in response from: " + encodedURI);
			}
			setBinaryBlock(get.getResponseBody(), contentTypeValue);
		}
	} catch (Exception e) {
		logger.error("loadContentFromURL: " + encodedURI, e);
		returnValue = false;
	} finally {
		get.releaseConnection();
	}
	
	if( logger.isInfoEnabled()) {
		logger.info("loadContentFromURL: loaded " + componentName);
	}
	
	return returnValue;
}