Java源码示例:org.apache.http.protocol.RequestContent
示例1
private void configureHttpProcessorBuilder(final HttpClientBuilder builder, final WebRequest webRequest) {
final HttpProcessorBuilder b = HttpProcessorBuilder.create();
for (final HttpRequestInterceptor i : getHttpRequestInterceptors(webRequest)) {
b.add(i);
}
// These are the headers used in HttpClientBuilder, excluding the already added ones
// (RequestClientConnControl and RequestAddCookies)
b.addAll(new RequestDefaultHeaders(null),
new RequestContent(),
new RequestTargetHost(),
new RequestExpectContinue());
b.add(new RequestAcceptEncoding());
b.add(new RequestAuthCache());
b.add(new ResponseProcessCookies());
builder.setHttpProcessor(b.build());
}
示例2
@Test
public void postRequest() throws HttpException, IOException {
// Processor is required because it will determine the final request body including
// headers before outgoing.
RequestContent processor = new RequestContent();
Map<String, String> params = new HashMap<String, String>();
params.put("a", "1");
params.put("b", "2+");
params.put("c", "3 ");
HttpUriRequest request;
request = SentinelApiClient.postRequest("/test", params, false);
assertNotNull(request);
processor.process(request, null);
assertNotNull(request.getFirstHeader("Content-Type"));
assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue());
request = SentinelApiClient.postRequest("/test", params, true);
assertNotNull(request);
processor.process(request, null);
assertNotNull(request.getFirstHeader("Content-Type"));
assertEquals("application/x-www-form-urlencoded; charset=UTF-8", request.getFirstHeader("Content-Type").getValue());
}
示例3
public static CloseableHttpClient create(RequestConfig config, HttpRequestRetryHandler retryHandler, HttpClientConnectionManager connectionManager) {
HttpClientBuilder builder = HttpClientBuilder.create();
builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
if (config != null)
builder.setDefaultRequestConfig(config);
if (retryHandler != null)
builder.setRetryHandler(retryHandler);
if (connectionManager != null)
builder.setConnectionManager(connectionManager);
return builder.build();
}
示例4
public static CloseableHttpAsyncClient create(RequestConfig config, NHttpClientConnectionManager connectionManager) {
HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
if (config != null)
builder.setDefaultRequestConfig(config);
if (connectionManager != null)
builder.setConnectionManager(connectionManager);
return builder.build();
}
示例5
private void initialize() {
if (initialized.getAndSet(true)) {
return;
}
IOReactorConfig.Builder config = createConfig();
// params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0");
final ConnectingIOReactor ioReactor = createIoReactor(config);
createSslContext();
int socketBufferSize = Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024);
final ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(socketBufferSize).build();
BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, connectionConfig);
pool = new BasicNIOConnPool(ioReactor, nioConnFactory, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000));
pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500));
pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500));
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, connectionConfig);
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
}, "jsonrpc4j HTTP IOReactor");
t.setDaemon(true);
t.start();
HttpProcessor httpProcessor = new ImmutableHttpProcessor(new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(false));
requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy());
}
示例6
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();
}
}