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

The following examples show how to use org.apache.commons.httpclient.methods.GetMethod#addRequestHeader() . 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: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindUsersByProperty() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    method.setQueryString(new NameValuePair[] { new NameValuePair("telMobile", "39847592"), new NameValuePair("gender", "Female"),
            new NameValuePair("birthDay", "12/12/2009") });
    method.addRequestHeader("Accept-Language", "en");
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
}
 
Example 2
Source File: AbstractTestRestApi.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected static GetMethod httpGet(String path, String user, String pwd, String cookies)
        throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  GetMethod getMethod = new GetMethod(URL + path);
  getMethod.addRequestHeader("Origin", URL);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    getMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  if (!StringUtils.isBlank(cookies)) {
    getMethod.setRequestHeader("Cookie", getMethod.getResponseHeader("Cookie") + ";" + cookies);
  }
  httpClient.executeMethod(getMethod);
  LOG.info("{} - {}", getMethod.getStatusCode(), getMethod.getStatusText());
  return getMethod;
}
 
Example 3
Source File: PublicApiHttpClient.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public HttpResponse get(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
            final String relationCollectionName, final Object relationshipEntityId, Map<String, String> params, Map<String, String> headers) throws IOException
{
    if (headers == null)
    {
        headers = Collections.emptyMap();
    }

    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, params);
    String url = endpoint.getUrl();

    GetMethod req = new GetMethod(url);

    for (Entry<String, String> header : headers.entrySet())
    {
        req.addRequestHeader(header.getKey(), header.getValue());
    }

    return submitRequest(req, rq);
}
 
Example 4
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected static GetMethod httpGet(String path, String user, String pwd, String cookies)
    throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  GetMethod getMethod = new GetMethod(URL + path);
  getMethod.addRequestHeader("Origin", URL);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    getMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  if (!StringUtils.isBlank(cookies)) {
    getMethod.setRequestHeader("Cookie", getMethod.getResponseHeader("Cookie") + ";" + cookies);
  }
  httpClient.executeMethod(getMethod);
  LOG.info("{} - {}", getMethod.getStatusCode(), getMethod.getStatusText());
  return getMethod;
}
 
Example 5
Source File: SecurityRestApiTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUserList() throws IOException {
  GetMethod get = httpGet("/security/userlist/admi", "admin", "password1");
  get.addRequestHeader("Origin", "http://localhost");
  Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(),
      new TypeToken<Map<String, Object>>(){}.getType());
  List<String> userList = (List) ((Map) resp.get("body")).get("users");
  collector.checkThat("Search result size", userList.size(),
      CoreMatchers.equalTo(1));
  collector.checkThat("Search result contains admin", userList.contains("admin"),
      CoreMatchers.equalTo(true));
  get.releaseConnection();

  GetMethod notUser = httpGet("/security/userlist/randomString", "admin", "password1");
  notUser.addRequestHeader("Origin", "http://localhost");
  Map<String, Object> notUserResp = gson.fromJson(notUser.getResponseBodyAsString(),
      new TypeToken<Map<String, Object>>(){}.getType());
  List<String> emptyUserList = (List) ((Map) notUserResp.get("body")).get("users");
  collector.checkThat("Search result size", emptyUserList.size(),
      CoreMatchers.equalTo(0));

  notUser.releaseConnection();
}
 
Example 6
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_UserRequiredWithUser() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/user/test-auth").toString());
  get.addRequestHeader(VmApiProxyEnvironment.EMAIL_HEADER, "[email protected]");
  get.addRequestHeader(VmApiProxyEnvironment.AUTH_DOMAIN_HEADER, "google.com");
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("[email protected]: [email protected]", get.getResponseBodyAsString());
}
 
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: HttpClientUtil.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
public String get(String url, String cookies, boolean followRedirects) throws
            IOException {
//        clearCookies();
        GetMethod g = new GetMethod(url);
        g.setFollowRedirects(followRedirects);
        if (StringUtils.isNotEmpty(cookies)) {
            g.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(g);
        return g.getResponseBodyAsString();
    }
 
Example 9
Source File: HttpClientUtil.java    From spider with GNU General Public License v3.0 5 votes vote down vote up
public String get(String url, String cookies) throws
            IOException {
//        clearCookies();
        GetMethod g = new GetMethod(url);
        g.setFollowRedirects(false);
        if (StringUtils.isNotEmpty(cookies)) {
            g.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(g);
        return g.getResponseBodyAsString();
    }
 
Example 10
Source File: OAuth2TenantInitializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getTenantName(String organizationId) {
	try {
		OAuth2Client oauth2Client = new OAuth2Client();

		String token = oauth2Client.getAdminToken();

		HttpClient httpClient = oauth2Client.getHttpClient();
		String url = config.getProperty("REST_BASE_URL") + config.getProperty("ORGANIZATION_INFO_PATH") + organizationId;
		GetMethod httpget = new GetMethod(url);
		httpget.addRequestHeader("X-Auth-Token", token);

		int statusCode = httpClient.executeMethod(httpget);
		byte[] response = httpget.getResponseBody();
		if (statusCode != HttpStatus.SC_OK) {
			logger.error("Error while getting the name of organization with id [" + organizationId + "]: server returned statusCode = " + statusCode);
			LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });
			throw new SpagoBIRuntimeException(
					"Error while getting the name of organization with id [" + organizationId + "]: server returned statusCode = " + statusCode);
		}

		String responseStr = new String(response);
		LogMF.debug(logger, "Server response is:\n{0}", responseStr);
		JSONObject jsonObject = new JSONObject(responseStr);

		return jsonObject.getJSONObject("project").getString("name");
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to obtain tenant' name from IdM REST API", e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 11
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_UntrustedInboundIpWithQuery() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrlForHostIP("/admin/test-auth?foo=bar").toString());
  get.addRequestHeader(VmApiProxyEnvironment.REAL_IP_HEADER, "127.0.0.2"); // Force untrusted dev IP
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(307, httpCode);
  assertEquals("https://testversion-dot-testbackend-dot-testhostname/admin/test-auth?foo=bar",
          get.getResponseHeader("Location").getValue());
}
 
Example 12
Source File: HttpClientUtil.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
public String get(String url, String cookies, boolean followRedirects) throws
            IOException {
//        clearCookies();
        GetMethod g = new GetMethod(url);
        g.setFollowRedirects(followRedirects);
        if (StringUtils.isNotEmpty(cookies)) {
            g.addRequestHeader("cookie", cookies);
        }
        hc.executeMethod(g);
        return g.getResponseBodyAsString();
    }
 
Example 13
Source File: ZeppelinRestApiTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private String getNoteContent(String id) throws IOException {
  GetMethod get = httpGet("/notebook/export/" + id);
  assertThat(get, isAllowed());
  get.addRequestHeader("Origin", "http://localhost");
  Map<String, Object> resp =
      gson.fromJson(get.getResponseBodyAsString(),
          new TypeToken<Map<String, Object>>() {}.getType());
  assertEquals(200, get.getStatusCode());
  String body = resp.get("body").toString();
  // System.out.println("Body is " + body);
  get.releaseConnection();
  return body;
}
 
Example 14
Source File: VmRuntimeJettyKitchenSinkTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testSsl_WithSSL() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/test-ssl").toString());
  get.addRequestHeader(VmApiProxyEnvironment.HTTPS_HEADER, "on");
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("true:https:https://localhost/test-ssl", get.getResponseBodyAsString());
}
 
Example 15
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_UntrustedRealIP() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/admin/test-auth").toString());
  get.addRequestHeader(VmApiProxyEnvironment.REAL_IP_HEADER, "123.123.123.123");
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(307, httpCode);
  assertEquals("https://testversion-dot-testbackend-dot-testhostname/admin/test-auth",
          get.getResponseHeader("Location").getValue());
}
 
Example 16
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_UserRequiredWithAdmin() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/user/test-auth").toString());
  get.addRequestHeader(VmApiProxyEnvironment.EMAIL_HEADER, "[email protected]");
  get.addRequestHeader(VmApiProxyEnvironment.AUTH_DOMAIN_HEADER, "google.com");
  get.addRequestHeader(VmApiProxyEnvironment.IS_ADMIN_HEADER, "1");

  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("[email protected]: [email protected]", get.getResponseBodyAsString());
}
 
Example 17
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_AdminRequiredNoUser_TaskQueueHeader() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/admin/test-auth").toString());
  get.addRequestHeader("X-AppEngine-QueueName", "default");
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("null: null", get.getResponseBodyAsString());
}
 
Example 18
Source File: WebUtil.java    From Criteria2Query with Apache License 2.0 5 votes vote down vote up
public static String doGet(String url, String charset) throws Exception {  
System.out.println("url="+url);
     HttpClient client = new HttpClient();  
     GetMethod method = new GetMethod(url);  
	  
     if (null == url || !url.startsWith("http")) {  
         throw new Exception("请求地址格式不对");  
     }  
     // 设置请求的编码方式  
     if (null != charset) {  
         method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);  
     } else {  
         method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + "utf-8");  
     }  
     int statusCode = client.executeMethod(method);  
	  
     if (statusCode != HttpStatus.SC_OK) {// 打印服务器返回的状态  
         System.out.println("Method failed: " + method.getStatusLine());  
     }  
     
     byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());  
     // 在返回响应消息使用编码(utf-8或gb2312)  
     String response = new String(responseBody, "utf-8"); 
    
 
     
     System.out.println("------------------response:" + response);  
     // 释放连接  
     method.releaseConnection();  
     return response;  
 }
 
Example 19
Source File: VmRuntimeJettyAuthTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAuth_AdminRequiredWithNonAdmin() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  GetMethod get = new GetMethod(createUrl("/admin/test-auth").toString());
  get.addRequestHeader(VmApiProxyEnvironment.EMAIL_HEADER, "[email protected]");
  get.addRequestHeader(VmApiProxyEnvironment.AUTH_DOMAIN_HEADER, "google.com");
  get.setFollowRedirects(false);
  int httpCode = httpClient.executeMethod(get);
  assertEquals(403, httpCode);
}
 
Example 20
Source File: VmRuntimeJettySessionTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testSsl_WithSSL() throws Exception {
  HttpClient httpClient = new HttpClient();
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  URL url = createUrl("/test-ssl");
  GetMethod get = new GetMethod(url.toString());
  get.addRequestHeader(VmApiProxyEnvironment.HTTPS_HEADER, "on");
  int httpCode = httpClient.executeMethod(get);
  assertEquals(200, httpCode);
  assertEquals("true:https:https://localhost/test-ssl", get.getResponseBodyAsString());
}