org.apache.http.message.BasicHttpRequest Java Examples

The following examples show how to use org.apache.http.message.BasicHttpRequest. 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: ApiServerTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
private static void checkEndpoints(URI server, Map<String, String> endpoints) throws Exception {
    HttpHost host = new HttpHost(server.getHost(), server.getPort());
    for (Map.Entry<String, String> entry : endpoints.entrySet()) {
        HttpResponse response = HttpClientBuilder.create().build()
                .execute(host, new BasicHttpRequest("GET", entry.getKey()));
        if (entry.getValue() == null) {
            // Verify return value 404 only
            Assert.assertEquals(entry.getKey() + ": " + endpoints.toString(),
                    404, response.getStatusLine().getStatusCode());
        } else if (entry.getValue().isEmpty()) {
            // Verify return value 200 only
            Assert.assertEquals(entry.getKey() + ": " + endpoints.toString(),
                    200, response.getStatusLine().getStatusCode());
        } else {
            // Verify content and return value
            Assert.assertEquals(entry.getKey() + ": " + endpoints.toString(), entry.getValue(), new ContentResponseHandler()
                    .handleEntity(response.getEntity())
                    .asString());
            Assert.assertEquals(entry.getKey() + ": " + endpoints.toString(),
                    200, response.getStatusLine().getStatusCode());
        }
    }
}
 
Example #2
Source File: UpnpHttpRequestFactory.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException {
    if (isOneOf(BASIC, method)) {
        return new BasicHttpRequest(method, uri);
    } else if (isOneOf(WITH_ENTITY, method)) {
        return new BasicHttpEntityEnclosingRequest(method, uri);
    } else {
        return super.newHttpRequest(method, uri);
    }
}
 
Example #3
Source File: TracedHttpClientTest.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUrlHttpHostHttpRequest() {
    assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com"), new BasicHttpRequest("GET", "/")), is("http://amazon.com/"));
    assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com", -1, "https"), new BasicHttpRequest("GET", "/")), is("https://amazon.com/"));
    assertThat(TracedHttpClient.getUrl(new HttpHost("localhost", 8080), new BasicHttpRequest("GET", "/api/v1")), is("http://localhost:8080/api/v1"));
    assertThat(TracedHttpClient.getUrl(new HttpHost("localhost", 8443, "https"), new BasicHttpRequest("GET", "/api/v1")), is("https://localhost:8443/api/v1"));

    assertThat(TracedHttpClient.getUrl(new HttpHost("amazon.com", -1, "https"), new BasicHttpRequest("GET", "https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html")), is("https://docs.aws.amazon.com/xray/latest/devguide/xray-api.html"));
}
 
Example #4
Source File: ConnectionReuseTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
    throws IOException, HttpException {
  HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);

  req.addHeader("Host", target.getHostName());
  if (!conn.isOpen()) {
    // establish connection based on its route info
    cm.connect(conn, route, 1000, context);
    // and mark it as route complete
    cm.routeComplete(conn, route, context);
  }
  conn.sendRequestHeader(req);
  conn.flush();
  conn.receiveResponseHeader();
}
 
Example #5
Source File: UpnpHttpRequestFactory.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException {
    if (isOneOf(BASIC, method)) {
        return new BasicHttpRequest(method, uri);
    } else if (isOneOf(WITH_ENTITY, method)) {
        return new BasicHttpEntityEnclosingRequest(method, uri);
    } else {
        return super.newHttpRequest(method, uri);
    }
}
 
Example #6
Source File: HttpCommandEffectorHttpBinTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map();
    BasicHttpRequest req = (BasicHttpRequest)request;
    String url = req.getRequestLine().getUri();
    URI uri = URI.create(url);
    String method = req.getRequestLine().getMethod();
    boolean expectsPost = uri.getPath().equals("/post");
    if (expectsPost && !method.equals("POST") ||
            !expectsPost && !method.equals("GET")) {
        throw new IllegalStateException("Method " + method + " not allowed on " + url);
    }
    List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
    if (!params.isEmpty()) {
        j.push().at("args");
        for (NameValuePair param : params) {
            j.put(param.getName(), param.getValue());
        }
        j.pop();
    }
    j.put("origin", "127.0.0.1");
    j.put("url", serverUrl + url);

    response.setHeader("Content-Type", "application/json");
    response.setStatusCode(200);
    response.setEntity(new StringEntity(j.toString()));
}
 
Example #7
Source File: SecureClusterTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void basicGetUserHomeRequest() throws Exception {
  setupLogging();
  CloseableHttpClient client = getHttpClient();
  String method = "GET";
  String uri = driver.getClusterUrl() + "/webhdfs/v1?op=GETHOMEDIRECTORY";
  HttpHost target = new HttpHost("localhost", driver.getGatewayPort(), "http");
  HttpRequest request = new BasicHttpRequest(method, uri);
  CloseableHttpResponse response = client.execute(target, request);
  String json = EntityUtils.toString(response.getEntity());
  response.close();
  assertEquals("{\"Path\":\"/user/" + userName + "\"}", json);
}
 
Example #8
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the CONNECT request for tunnelling.
 * Called by {@link #createTunnelToTarget createTunnelToTarget}.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  the CONNECT request for tunnelling
 */
protected HttpRequest createConnectRequest(HttpRoute route,
                                           HttpContext context) {
    // see RFC 2817, section 5.2 and
    // INTERNET-DRAFT: Tunneling TCP based protocols through
    // Web proxy servers

    HttpHost target = route.getTargetHost();

    String host = target.getHostName();
    int port = target.getPort();
    if (port < 0) {
        Scheme scheme = connManager.getSchemeRegistry().
            getScheme(target.getSchemeName());
        port = scheme.getDefaultPort();
    }

    StringBuilder buffer = new StringBuilder(host.length() + 6);
    buffer.append(host);
    buffer.append(':');
    buffer.append(Integer.toString(port));

    String authority = buffer.toString();
    ProtocolVersion ver = HttpProtocolParams.getVersion(params);
    HttpRequest req = new BasicHttpRequest("CONNECT", authority, ver);

    return req;
}
 
Example #9
Source File: TraceeHttpRequestInterceptorTest.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testRequestInterceptorWritesTraceeContextToRequestHeader() throws Exception {
	final HttpRequest httpRequest = new BasicHttpRequest("GET", "http://localhost/pew");

	backend.put("foo", "bar");

	unit.process(httpRequest, mock(HttpContext.class));

	assertThat("HttpRequest contains TracEE Context Header", httpRequest.containsHeader(TraceeConstants.TPIC_HEADER), equalTo(true));
	assertThat(httpRequest.getFirstHeader(TraceeConstants.TPIC_HEADER).getValue(), equalTo("foo=bar"));
}
 
Example #10
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
public String handleSsoGetRequestURI(String samlRequestURI) {
    return handleSsoGetRequestBase(new BasicHttpRequest("GET", samlRequestURI));
}
 
Example #11
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
public void handleSloGetRequestURI(String samlRequestURI) {
    handleSloGetRequestBase(new BasicHttpRequest("GET", samlRequestURI));
}
 
Example #12
Source File: TestTwitterSocket.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
				Constants.ConsumerKey,
				Constants.ConsumerSecret);
	  consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret);
	  
	  
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是 
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("127.0.0.1", 1080);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "https://www.twitter.com"};
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        
	  
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
//        consumer.sign(request);
        
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
//        Header[] hs = response.getAllHeaders();
//        for (Header h : hs) {
//          System.out.println(h.getName() + ":" + h.getValue());
//        }
        // 输出主体信息
//        System.out.println(EntityUtils.toString(response.getEntity()));
        
        HttpEntity entry = response.getEntity();
        StringBuffer sb = new StringBuffer();
  	  if(entry != null)
  	  {
  	    InputStreamReader is = new InputStreamReader(entry.getContent());
  	    BufferedReader br = new BufferedReader(is);
  	    String str = null;
  	    while((str = br.readLine()) != null)
  	    {
  	     sb.append(str.trim());
  	    }
  	    br.close();
  	  }
  	  System.out.println(sb.toString());
  	  
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }
 
Example #13
Source File: AWSRequestSigningApacheInterceptorTest.java    From aws-request-signing-apache-interceptor with Apache License 2.0 4 votes vote down vote up
@Test(expected = IOException.class)
public void testBadRequest() throws Exception {

    HttpRequest badRequest = new BasicHttpRequest("GET", "?#!@*%");
    createInterceptor().process(badRequest, new BasicHttpContext());
}
 
Example #14
Source File: LocalRequestTest.java    From logbook with MIT License 4 votes vote down vote up
@Test
void shouldRetrieveRelativeUriForNonHttpUriRequests() {
    final LocalRequest unit = unit(new BasicHttpRequest("GET", "http://localhost/"));

    assertThat(unit, hasFeature("request uri", org.zalando.logbook.HttpRequest::getRequestUri, hasToString("http://localhost/")));
}
 
Example #15
Source File: ApacheHttp43SLR.java    From webarchive-commons with Apache License 2.0 4 votes vote down vote up
protected InputStream doSeekLoad(long offset, int maxLength, URL url)
          throws IOException {

try {
	SocketAddress endpoint = new InetSocketAddress(url.getHost(), getPort(url));
	
	socket = new Socket();
	socket.connect(endpoint, connectTimeout);
	
	activeConn = new DefaultBHttpClientConnection(BUFF_SIZE);
	activeConn.bind(socket);
	activeConn.setSocketTimeout(readTimeout);
	
	HttpRequest request = new BasicHttpRequest("GET", url.getFile(), HttpVersion.HTTP_1_1);
	
	String rangeHeader = makeRangeHeader(offset, maxLength);
	
	if (rangeHeader != null) {
		request.setHeader("Range", rangeHeader);
	}
	
	if (this.isNoKeepAlive()) {
		request.setHeader("Connection", "close");
	} else {
		request.setHeader("Connection", "keep-alive");
	}
	
	if (this.getCookie() != null) {
		request.setHeader("Cookie", this.getCookie());
	}
	
	request.setHeader("Accept", "*/*");
	request.setHeader("Host", url.getHost());
	
	activeConn.sendRequestHeader(request);
	activeConn.flush();
				
	response = activeConn.receiveResponseHeader();
	
	int code = response.getStatusLine().getStatusCode();
	
	connectedUrl = url.toString();
	
	if (code > 300 && code < 400) {
		Header header = response.getFirstHeader("Location");
		
		doClose();
		
		if (header != null) {
			URL redirectURL = new URL(header.getValue());
			return doSeekLoad(offset, maxLength, redirectURL);
		}
	}
	
	if (code != 200 && code != 206) {
		throw new BadHttpStatusException(code, connectedUrl + " " + rangeHeader);
	}
	
	activeConn.receiveResponseEntity(response);
	
	return response.getEntity().getContent();
	
} catch (HttpException e) {
	doClose();
	throw new IOException(e);
	
      } catch (IOException io) {
      	
	if (saveErrHeader != null) {
		errHeader = getHeaderValue(saveErrHeader);	
	}
	
	connectedUrl = url.toString();
	
	doClose();
	throw io;
      }
  }