下面列出了怎么用org.apache.http.params.CoreConnectionPNames的API类实例代码及写法,或者点击链接到github查看源代码。
public static String getRequestFromCompansion(String url){
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
HttpGet get = new HttpGet(url);
try{
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服务器成功地返回响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 获取服务器响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
} else {
// 如果服务器失败返回响应数据"error"
return "error";
}
}catch(Exception e){
// 捕获超时异常 并反馈给调用者
e.printStackTrace();
return "connection time out";
}finally{
httpClient.getConnectionManager().shutdown();
}
}
public void start() throws IOException {
log.info("Starting sample Axis2 server");
//To set the socket can be bound even though a previous connection is still in a timeout state.
if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
}
listenerManager = new ListenerManager();
listenerManager.init(cfgCtx);
listenerManager.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {
}
started = true;
}
public void onExecutionStart() throws AutomationFrameworkException {
serverManager = new Axis2ServerManager();
//To set the socket can be bound even though a previous connection is still in a timeout state.
if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
}
try {
serverManager.start();
log.info(".................Deploying services..............");
serverManager.deployService(ServiceNameConstants.LB_SERVICE_1);
serverManager.deployService(ServiceNameConstants.SIMPLE_STOCK_QUOTE_SERVICE);
serverManager.deployService(ServiceNameConstants.SECURE_STOCK_QUOTE_SERVICE);
serverManager.deployService(ServiceNameConstants.SIMPLE_AXIS2_SERVICE);
} catch (IOException e) {
handleException("Error While Deploying services", e);
}
}
/**
* constructor.
*/
public static HttpResponse getSignWeight(String httpNode, String transactionSignString) {
try {
String requestUrl = "http://" + httpNode + "/wallet/getsignweight";
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
httppost = new HttpPost(requestUrl);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Connection", "Close");
if (transactionSignString != null) {
StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
}
response = httpClient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
//httppost.releaseConnection();
return response;
}
/**
* constructor.
*/
public static HttpResponse getTransactionApprovedList(String httpNode,
String transactionSignString) {
try {
String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist";
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
httppost = new HttpPost(requestUrl);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Connection", "Close");
if (transactionSignString != null) {
StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
}
response = httpClient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
//httppost.releaseConnection();
return response;
}
/**
* constructor.
*/
public static HttpResponse createConnect(String url, JsonObject requestBody) {
try {
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Connection", "Close");
if (requestBody != null) {
StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
}
response = httpClient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
return response;
}
/**
* constructor.
*/
public static HttpResponse createConnect1(String url, JSONObject requestBody) {
try {
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
connectionTimeout * 10000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000);
httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Connection", "Close");
if (requestBody != null) {
StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
}
response = httpClient.execute(httppost);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
return response;
}
synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {
try {
this.router = router;
this.serverSocket =
new ServerSocket(
configuration.getListenPort(),
configuration.getTcpConnectionBacklog(),
bindAddress
);
log.info("Created socket (for receiving TCP streams) on: " + serverSocket.getLocalSocketAddress());
this.globalParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configuration.getDataWaitTimeoutSeconds() * 1000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, configuration.getBufferSizeKilobytes() * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, configuration.isStaleConnectionCheck())
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, configuration.isTcpNoDelay());
} catch (Exception ex) {
throw new InitializationException("Could not initialize "+getClass().getSimpleName()+": " + ex.toString(), ex);
}
}
@Test
public void testIncompleteWrite() throws Exception {
PostEndpoint.invoked = false;
//make sure incomplete writes do not block threads
//and that incoplete data is not delivered to the endpoint
for (int i = 0; i < 1000; ++i) {
Socket socket = new Socket(url.getHost(), url.getPort());
socket.getOutputStream().write(
"POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:10\r\n\r\ntest".getBytes(StandardCharsets.UTF_8));
socket.getOutputStream().flush();
socket.getOutputStream().close();
socket.close();
}
Assertions.assertFalse(PostEndpoint.invoked);
RestAssuredConfig config = RestAssured.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)
.setParam(CoreConnectionPNames.SO_TIMEOUT, 1000));
RestAssured.given().config(config).get("/post").then().body(Matchers.is("ok"));
}
public void get() throws IOException {
String requesturl = "http://www.tuling123.com/openapi/api";
// 声明httpclient 每一个会话有一个独立的httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
StringBuilder params = new StringBuilder();
params.append(requesturl + "?");
params.append("key=" + URLEncoder.encode("4b441cb500f431adc6cc0cb650b4a5d0", REQUEST_CHARSET)).append("&");
params.append("info=" + URLEncoder.encode("4b441cb500f431adc6cc0cb650b4a5d0", REQUEST_CHARSET));
try {
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // 请求超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); // 读取超时
HttpGet httpGet = new HttpGet(params.toString());
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity, "utf-8");
log.info(content);
EntityUtils.consume(entity);
} catch (Exception e) {
log.error("" + e);
} finally {
if (response != null)
response.close();
}
}
/**
* 此处解释下MaxtTotal和DefaultMaxPerRoute的区别:
* 1、MaxtTotal是整个池子的大小;
* 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;比如:
* MaxtTotal=400 DefaultMaxPerRoute=200
* 而我只连接到http://sishuok.com时,到这个主机的并发最多只有200;而不是400;
* 而我连接到http://sishuok.com 和 http://qq.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400);所以起作用的设置是DefaultMaxPerRoute。
*/
public HttpParams getHttpParams() {
HttpParams params = new BasicHttpParams();
// 设置连接超时时间
Integer CONNECTION_TIMEOUT = 2 * 1000; // 设置请求超时2秒钟 根据业务调整
Integer SO_TIMEOUT = 2 * 1000; // 设置等待数据超时时间2秒钟 根据业务调整
// 定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间
// 这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置,默认等于CONNECTION_TIMEOUT,因此一定要设置
Long CONN_MANAGER_TIMEOUT = 500L; // 该值就是连接不够用的时候等待超时时间,一定要设置,而且不能太大 ()
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
// 在提交请求之前 测试连接是否可用
params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
return params;
}
/**
* HTTP GET
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpGet(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.GET, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpGet get = new HttpGet(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
get.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
return convert(httpClient.execute(get));
}
/**
* HTTP POST表单
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param bodys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
if (headers == null) {
headers = new HashMap<String, String>();
}
headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_FORM);
headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, bodys, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPost post = new HttpPost(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
UrlEncodedFormEntity formEntity = buildFormEntity(bodys);
if (formEntity != null) {
post.setEntity(formEntity);
}
return convert(httpClient.execute(post));
}
/**
* Http POST 字符串
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param body
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPost post = new HttpPost(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
if (StringUtils.isNotBlank(body)) {
post.setEntity(new StringEntity(body, Constants.ENCODING));
}
return convert(httpClient.execute(post));
}
/**
* HTTP POST 字节数组
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param bodys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPost post = new HttpPost(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
if (bodys != null) {
post.setEntity(new ByteArrayEntity(bodys));
}
return convert(httpClient.execute(post));
}
/**
* HTTP PUT 字符串
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param body
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPut put = new HttpPut(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
if (StringUtils.isNotBlank(body)) {
put.setEntity(new StringEntity(body, Constants.ENCODING));
}
return convert(httpClient.execute(put));
}
/**
* HTTP PUT字节数组
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param bodys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpPut put = new HttpPut(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
if (bodys != null) {
put.setEntity(new ByteArrayEntity(bodys));
}
return convert(httpClient.execute(put));
}
public void start() throws IOException {
log.info("Starting sample Axis2 server");
//To set the socket can be bound even though a previous connection is still in a timeout state.
if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
}
listenerManager = new ListenerManager();
listenerManager.init(cfgCtx);
listenerManager.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {
}
started = true;
}
public void onExecutionStart() throws AutomationFrameworkException {
serverManager = new Axis2ServerManager();
//To set the socket can be bound even though a previous connection is still in a timeout state.
if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
}
try {
serverManager.start();
log.info(".................Deploying services..............");
serverManager.deployService(ServiceNameConstants.LB_SERVICE_1);
serverManager.deployService(ServiceNameConstants.SIMPLE_STOCK_QUOTE_SERVICE);
serverManager.deployService(ServiceNameConstants.SECURE_STOCK_QUOTE_SERVICE);
serverManager.deployService(ServiceNameConstants.SIMPLE_AXIS2_SERVICE);
} catch (IOException e) {
handleException("Error While Deploying services", e);
}
}
synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {
try {
this.router = router;
this.serverSocket =
new ServerSocket(
configuration.getListenPort(),
configuration.getTcpConnectionBacklog(),
bindAddress
);
log.info("Created socket (for receiving TCP streams) on: " + serverSocket.getLocalSocketAddress());
this.globalParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configuration.getDataWaitTimeoutSeconds() * 1000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, configuration.getBufferSizeKilobytes() * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, configuration.isStaleConnectionCheck())
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, configuration.isTcpNoDelay());
} catch (Exception ex) {
throw new InitializationException("Could not initialize "+getClass().getSimpleName()+": " + ex.toString(), ex);
}
}
public static String myHttpGet(String url){
HttpClient httpClient = new DefaultHttpClient();
//设置超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
HttpGet get = new HttpGet(url);
try{
// 发送GET请求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服务器成功地返回响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 获取服务器响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
} else {
// 如果服务器失败返回响应数据"error"
return "error";
}
}catch(Exception e){
// 捕获超时异常 并反馈给调用者
e.printStackTrace();
return "connection time out";
}finally{
httpClient.getConnectionManager().shutdown();
}
}
/**
* Execute Http request and response code
* @param request - HTTP Request
* @param expectedCode - expected response code
* @return - response in JSONObject
*/
public JSON query(HttpRequestBase request, int expectedCode) throws IOException {
log.info("Requesting: " + request);
addRequiredHeader(request);
HttpParams requestParams = request.getParams();
requestParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT * 1000);
requestParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT * 1000);
synchronized (httpClient) {
String response;
try {
HttpResponse result = httpClient.execute(request);
int statusCode = result.getStatusLine().getStatusCode();
response = getResponseEntity(result);
if (statusCode != expectedCode) {
notifier.notifyAbout("Response with code " + statusCode + ": " + extractErrorMessage(response));
throw new IOException("API responded with wrong status code: " + statusCode);
} else {
log.debug("Response: " + response);
}
} finally {
request.abort();
}
if (response == null || response.isEmpty()) {
return JSONNull.getInstance();
} else {
return JSONSerializer.toJSON(response, new JsonConfig());
}
}
}
/**
* 简单的获取http get结果
* @param url
* @return
* @throws IOException
*/
public static String getUrl(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity, "UTF-8");
httpget.releaseConnection();
return html;
}
private static int httpNotification(String uri, int timeout)
throws IOException, URISyntaxException {
DefaultHttpClient client = new DefaultHttpClient();
client.getParams()
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout)
.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, (long) timeout);
HttpGet httpGet = new HttpGet(new URI(uri));
httpGet.setHeader("Accept", "*/*");
return client.execute(httpGet).getStatusLine().getStatusCode();
}
/**
* Gets the http connection read timeout in milliseconds.
*/
public long getConnectionTimeout() {
if (params == null) {
return 0;
}
return params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
}
/**
* HTTP DELETE
* @param host
* @param path
* @param connectTimeout
* @param headers
* @param querys
* @param signHeaderPrefixList
* @param appKey
* @param appSecret
* @return
* @throws Exception
*/
public static Response httpDelete(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, List<String> signHeaderPrefixList, String appKey, String appSecret)
throws Exception {
headers = initialBasicHeader(HttpMethod.DELETE, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);
HttpClient httpClient = wrapClient(host);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));
HttpDelete delete = new HttpDelete(initUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
delete.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
}
return convert(httpClient.execute(delete));
}
private static int httpNotification(String uri, int timeout)
throws IOException, URISyntaxException {
DefaultHttpClient client = new DefaultHttpClient();
client.getParams()
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout)
.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, (long) timeout);
HttpGet httpGet = new HttpGet(new URI(uri));
httpGet.setHeader("Accept", "*/*");
return client.execute(httpGet).getStatusLine().getStatusCode();
}
public ListenerThread(final ApiServer requestHandler, final int port) {
try {
_serverSocket = new ServerSocket(port);
} catch (final IOException ioex) {
s_logger.error("error initializing api server", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
public ListenerThread(final HttpRequestHandler requestHandler, final int port) {
_executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));
try {
_serverSocket = new ServerSocket(port);
} catch (final IOException ioex) {
s_logger.error("error initializing cluster service servlet container", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("/clusterservice", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
public static PostResult httpPost(String url, ArrayList<NameValuePair> pairs) {
PostResult postResult = new PostResult();
if(pairs == null || pairs.size() == 0){
postResult.setSuccess(false);
postResult.setResponseMsg("post date of the request params is null !");
return postResult;
}
try {
HttpPost httppost = new HttpPost(url);
httppost.addHeader("charset", HTTP.UTF_8);
httppost.setHeader("Accept", "application/json,text/x-json,application/jsonrequest,text/json");
HttpEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
httppost.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
String resString = EntityUtils.toString(response.getEntity());
postResult = parse(status, resString);
} catch (Exception e) {
Ln.i("NetworkHelper", "=== post Ln ===", e);
}
return postResult;
}