Java源码示例:org.apache.http.HttpVersion
示例1
/** Handles URLs predicted as malicious. */
private void blockedMaliciousSiteRequested() {
try {
HttpResponse response =
new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL");
HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD);
BufferedWriter bufferedWriter =
new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
bufferedWriter.write(response.getStatusLine().toString());
String headers =
"Proxy-agent: FilterProxy/1.0\r\n"
+ httpEntity.getContentType().toString()
+ "\r\n"
+ "Content-Length: "
+ httpEntity.getContentLength()
+ "\r\n\r\n";
bufferedWriter.write(headers);
// Pass index.html content
bufferedWriter.write(EntityUtils.toString(httpEntity));
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
logger.error("Error writing to client when requested a blocked site", e);
}
}
示例2
@Before
public void setUp() throws Exception{
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
mockStatic(HttpClients.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClients.custom()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("{\"data\":{\"puliclyaccessble\":false},\"input\":{\"endpoint\":\"http://123\"}}".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
示例3
@Before
public void setUp() throws Exception{
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("lucene_version".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
示例4
@Before
public void setUp() throws Exception{
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("success".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
示例5
protected HttpParams getRequestParams(StreamRequestMessage requestMessage) {
HttpParams localParams = new BasicHttpParams();
localParams.setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
requestMessage.getOperation().getHttpMinorVersion() == 0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1
);
// DefaultHttpClient adds HOST header automatically in its default processor
// Add the default user agent if not already set on the message
if (!requestMessage.getHeaders().containsKey(UpnpHeader.Type.USER_AGENT)) {
HttpProtocolParams.setUserAgent(
localParams,
getConfiguration().getUserAgentValue(requestMessage.getUdaMajorVersion(), requestMessage.getUdaMinorVersion())
);
}
return new DefaultedHttpParams(localParams, globalParams);
}
示例6
/**
* 创建一个{@link HttpSendClient} 实例
* <p>
* 多态
*
* @return
*/
public HttpSendClient newHttpSendClient() {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeOut());
HttpConnectionParams.setSoTimeout(params, getSoTimeOut());
// HttpConnectionParams.setLinger(params, 1);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
// 解释: 握手的目的,是为了允许客户端在发送请求内容之前,判断源服务器是否愿意接受请求(基于请求头部)。
// Expect:100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题。
// 默认开启
// HttpProtocolParams.setUseExpectContinue(params, false);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSocketBufferSize(params, getSocketBufferSize());
ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
threadSafeClientConnManager.setMaxTotal(getMaxTotalConnections());
threadSafeClientConnManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());
DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(getRetryCount(), false);
DefaultHttpClient httpClient = new DefaultHttpClient(threadSafeClientConnManager, params);
httpClient.setHttpRequestRetryHandler(retryHandler);
return new HttpSendClient(httpClient);
}
示例7
/**
* 设置默认请求参数,并返回HttpClient
*
* @return HttpClient
*/
private HttpClient createHttpClient() {
HttpParams mDefaultHttpParams = new BasicHttpParams();
//设置连接超时
HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
//设置请求超时
HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000);
HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
//持续握手
HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
return mHttpClient;
}
示例8
@Test
public void TestHttpTransport() throws IOException {
HttpClient httpClient = mock(HttpClient.class);
org.apache.http.HttpResponse httpResponse = mock(org.apache.http.HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(200);
when(statusLine.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
when(statusLine.getReasonPhrase()).thenReturn("OK");
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(httpResponse.getEntity()).thenReturn(new StringEntity("Test", ContentType.APPLICATION_JSON));
HttpTransportImpl httpTransport = new HttpTransportImpl();
httpTransport.setHttpClient(httpClient);
when(httpClient.execute(Mockito.any())).thenReturn(httpResponse);
HttpRequest httpRequest = new HttpRequest("111", null, null);
HttpResponse actualResponse = httpTransport.get(httpRequest);
Assert.assertNotNull(actualResponse);
Assert.assertEquals(200, actualResponse.getStatusCode());
Assert.assertEquals("OK", actualResponse.getMessage());
Assert.assertEquals("Test", actualResponse.getContent());
}
示例9
@SuppressWarnings("resource")
private static OAuthRefreshTokenOnFailProcessor createProcessor(final String... grantJsons) throws IOException {
final CloseableHttpClient client = mock(CloseableHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
final HttpEntity first = entity(grantJsons[0]);
final HttpEntity[] rest = Arrays.stream(grantJsons).skip(1).map(OAuthRefreshTokenOnFailProcessorTest::entity)
.toArray(HttpEntity[]::new);
when(response.getEntity()).thenReturn(first, rest);
when(client.execute(ArgumentMatchers.any(HttpUriRequest.class))).thenReturn(response);
final Configuration configuration = configuration("403");
final OAuthRefreshTokenOnFailProcessor processor = new OAuthRefreshTokenOnFailProcessor(OAuthState.createFrom(configuration), configuration) {
@Override
CloseableHttpClient createHttpClient() {
return client;
}
};
return processor;
}
示例10
@Before
public void setUp() throws IOException {
AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));
mockClient = Mockito.mock(SdkHttpClient.class);
HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
resp.setEntity(entity);
Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));
ClientConfiguration clientConfig = new ClientConfiguration();
client = new GenericApiGatewayClientBuilder()
.withClientConfiguration(clientConfig)
.withCredentials(credentials)
.withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
.withRegion(Region.getRegion(Regions.fromName("us-east-1")))
.withApiKey("12345")
.withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
.build();
}
示例11
@Test
public void testExecute_non2xx_exception() throws IOException {
HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
resp.setEntity(entity);
Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));
Map<String, String> headers = new HashMap<>();
headers.put("Account-Id", "fubar");
headers.put("Content-Type", "application/json");
try {
client.execute(
new GenericApiGatewayRequestBuilder()
.withBody(new ByteArrayInputStream("test request".getBytes()))
.withHttpMethod(HttpMethodName.POST)
.withHeaders(headers)
.withResourcePath("/test/orders").build());
Assert.fail("Expected exception");
} catch (GenericApiGatewayException e) {
assertEquals("Wrong status code", 404, e.getStatusCode());
assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
}
}
示例12
private HttpParams createHttpParams() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, false);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(3));
ConnManagerParams.setMaxTotalConnections(params, 3);
ConnManagerParams.setTimeout(params, 1000);
HttpConnectionParams.setConnectionTimeout(params, 30000);
HttpConnectionParams.setSoTimeout(params, 30000);
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpClientParams.setRedirecting(params, false);
return params;
}
示例13
public synchronized static DefaultHttpClient getHttpClient() {
try {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// 超时设置
// 从连接池中取连接的超时时间
ConnManagerParams.setTimeout(params, 10000); // 连接超时
HttpConnectionParams.setConnectionTimeout(params, 10000); // 请求超时
HttpConnectionParams.setSoTimeout(params, 30000);
SchemeRegistry registry = new SchemeRegistry();
Scheme sch1 = new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80);
registry.register(sch1);
// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, registry);
mHttpClient = new DefaultHttpClient(conMgr, params);
} catch (Exception e) {
e.printStackTrace();
}
return mHttpClient;
}
示例14
/**
* Loads the configuration from the RuneScape website.
*/
public void load() throws IOException {
parameters.clear();
String text = normalize(Request.Get(CONFIG_URL)
.version(HttpVersion.HTTP_1_1)
.userAgent(USER_AGENT)
.useExpectContinue()
.execute()
.returnContent().toString());
String[] lines = text.split("\n");
for (String line : lines) {
extractKVPairInto(parameters, line);
}
String mainClass = parameters.get("initial_class");
setMainClass(mainClass.replace(".class", ""));
setDocumentBase(parameters.get("codebase"));
setArchiveName(parameters.get("initial_jar"));
}
示例15
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
示例16
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
示例17
/**
* Gets getUrl DefaultHttpClient which trusts getUrl set of certificates specified by the KeyStore
*
* @param keyStore custom provided KeyStore instance
* @return DefaultHttpClient
*/
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
try {
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
示例18
public static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java");
HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0");
httppost.setHeader("Cookie", cookies.toString());
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("multiupload_file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("Now uploading your file into zoho docs...........................");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
String tmp = EntityUtils.toString(resEntity);
// System.out.println(tmp);
if(tmp.contains("File Uploaded Successfully"))
System.out.println("File Uploaded Successfully");
}
// uploadresponse = response.getLastHeader("Location").getValue();
// System.out.println("Upload response : " + uploadresponse);
}
示例19
private DefaultHttpClient createHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpConnectionParams.setConnectionTimeout(params,
CONNETED_TIMEOUT * 1000);
HttpConnectionParams.setSoTimeout(params, CONNETED_TIMEOUT * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
ConnManagerParams.setMaxTotalConnections(params, 4);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
params, schReg);
return new DefaultHttpClient(connMgr, params);
}
示例20
private void post() throws IOException {
//以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优,
//请求中包含String类型的请求体并将响应内容作为byte[]返回
Request.Post("http://blog.csdn.net/vector_yi")
.useExpectContinue()
.version(HttpVersion.HTTP_1_1)
.bodyString("Important stuff", ContentType.DEFAULT_TEXT)
.execute().returnContent().asBytes();
//通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体
//将返回的响应内容存入文件
Request.Post("http://blog.csdn.net/vector_yi")
.addHeader("X-Custom-header", "stuff")
.viaProxy(new HttpHost("myproxy", 8080))
.bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
.execute().saveContent(new File("result.dump"));
Request.Post("http://targethost/login")
.bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
.execute().returnContent();
}
示例21
private static HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向
ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
return params;
}
示例22
@Before
public void initExecutor() throws IOException {
CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" ");
switch (mockReturnCode) {
case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
}
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
BasicHttpEntity entity = new BasicHttpEntity();
String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
entity.setContent(stream);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getEntity()).thenReturn(entity);
when(response.getStatusLine()).thenReturn(statusLine);
return response;
});
configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
示例23
private static HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向
ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
return params;
}
示例24
@Test
public void testDoGet() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Sample Server Response";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
String url = "https://localhost:4443/sample.html";
String out = httpDriver.doGet(url);
Assert.assertEquals(out, data);
}
示例25
@Test
public void testDoPost201() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Sample Server Response";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "OK" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", "value"));
String url = "https://localhost:4443/sample";
String out = httpDriver.doPost(url, params);
Assert.assertEquals(out, data);
}
示例26
@Test
public void testDoPost404() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Not Found";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", "value"));
String url = "https://localhost:4443/sample";
String out = httpDriver.doPost(url, params);
Assert.assertEquals(out, "");
}
示例27
/**
* Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
*
* @param keyStore custom provided KeyStore instance
* @return DefaultHttpClient
*/
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
try {
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
示例28
@Test
public void testGetBusinessObjectDataAssertNoAuthorizationHeaderWhenNoSsl() throws Exception
{
HttpClientOperations mockHttpClientOperations = mock(HttpClientOperations.class);
HttpClientOperations originalHttpClientOperations = (HttpClientOperations) ReflectionTestUtils.getField(downloaderWebClient, "httpClientOperations");
ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", mockHttpClientOperations);
try
{
CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
when(mockHttpClientOperations.execute(any(), any())).thenReturn(closeableHttpResponse);
when(closeableHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity(xmlHelper.objectToXml(new BusinessObjectData())));
DownloaderInputManifestDto manifest = new DownloaderInputManifestDto();
downloaderWebClient.getRegServerAccessParamsDto().setUseSsl(false);
downloaderWebClient.getBusinessObjectData(manifest);
verify(mockHttpClientOperations).execute(any(), argThat(httpUriRequest -> httpUriRequest.getFirstHeader("Authorization") == null));
}
finally
{
ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", originalHttpClientOperations);
}
}
示例29
private static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
示例30
/**
* Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
*
* @param keyStore custom provided KeyStore instance
* @return DefaultHttpClient
*/
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
try {
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}