想了解不建议使用httpClient.getConnectionManager的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于-应该改用什么?的相关问题,此外,我们还将为您介绍关于.conn
想了解不建议使用httpClient.getConnectionManager的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于-应该改用什么?的相关问题,此外,我们还将为您介绍关于.conn.ManagedClientConnectionImpl@604ed9f0 java.net.ConnectException: Connection refused: connect、Android 网络提交数据 (HttpConnection HttpClient) POST GET 方式、apache HttpClient API中的setConnectionTimeout,setSoTimeout和“ http.connection- manager.timeout”之间有什么区别、Apache PoolingHttpClientConnectionManager引发非法状态异常的新知识。
本文目录一览:- 不建议使用httpClient.getConnectionManager()-应该改用什么?(http方法不应该禁用)
- .conn.ManagedClientConnectionImpl@604ed9f0 java.net.ConnectException: Connection refused: connect
- Android 网络提交数据 (HttpConnection HttpClient) POST GET 方式
- apache HttpClient API中的setConnectionTimeout,setSoTimeout和“ http.connection- manager.timeout”之间有什么区别
- Apache PoolingHttpClientConnectionManager引发非法状态异常
不建议使用httpClient.getConnectionManager()-应该改用什么?(http方法不应该禁用)
我已经继承了代码
import org.apache.http.client.HttpClient;...HttpClient httpclient = createHttpClientOrProxy(); try { HttpPost postRequest = postRequest(data, url); body = readResponseIntoBody(body, httpclient, postRequest); } catch( IOException ioe ) { throw new RuntimeException("Cannot post/read", ioe); } finally { httpclient.getConnectionManager().shutdown(); // ** Deprecated }private HttpClient createHttpClientOrProxy() { HttpClient httpclient = new DefaultHttpClient(); /* * Set an HTTP proxy if it is specified in system properties. * * http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html * http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientExecuteProxy.java */ if( isSet(System.getProperty("http.proxyHost")) ) { log.warn("http.proxyHost = " + System.getProperty("http.proxyHost") ); log.warn("http.proxyPort = " + System.getProperty("http.proxyPort")); int port = 80; if( isSet(System.getProperty("http.proxyPort")) ) { port = Integer.parseInt(System.getProperty("http.proxyPort")); } HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), port, "http");// @Deprecated methods here... getParams() and ConnRoutePNames httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } return httpclient;}
getConnectionManager()
读为“
@DeprecatedClientConnectionManager getConnectionManager()Deprecated. (4.3) use HttpClientBuilder.Obtains the connection manager used by this client.
HttpClientBuilder的文档似乎很稀疏,只是说:
Builder for CloseableHttpClient instances.
但是,如果我HttpClient
用CloseableHttpClient
该方法替换仍然出现@Deprecated
。
如何使用不推荐使用的方法?
答案1
小编典典不用创建的新实例,而是HttpClient
使用Builder。你会得到一个CloseableHttpClient
。
例如用法:
CloseableHttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build()
而不是使用getConnectionManager().shutdown()
,而是使用close()
方法CloseableHttpClient
。
.conn.ManagedClientConnectionImpl@604ed9f0 java.net.ConnectException: Connection refused: connect
DEBUG 2016-11-07 14:32:47,518 Get connection for route {}->http://127.0.0.1:8087->http://rdsearch.zhaopin.com:80DEBUG 2016-11-07 14:32:47,519 Connecting to 127.0.0.1:8087
DEBUG 2016-11-07 14:32:48,530 Connection org.apache.http.impl.conn.DefaultClientConnection@91161c7 closed
DEBUG 2016-11-07 14:32:48,531 Connection org.apache.http.impl.conn.DefaultClientConnection@91161c7 shut down
DEBUG 2016-11-07 14:32:48,532 Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@604ed9f0
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:117)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:882)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
Android 网络提交数据 (HttpConnection HttpClient) POST GET 方式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget38"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:textSize="18sp" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:textSize="18sp" />
<Button
android:id="@+id/btn_get"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1000"
android:text="GET提交" />
<Button
android:id="@+id/btn_post"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1000"
android:text="POST提交" />
<Button
android:id="@+id/btn_get_httpclient"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1000"
android:text="HttpClient Get提交" />
<Button
android:id="@+id/btn_post_httpclient"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1000"
android:text="HttpClient POST提交" />
</LinearLayout>
package com.pas.postdata;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.pas.htmlview.utils.StreamTools;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText et_username;
private EditText et_password;
private final int SHOWINFO = 0;
private final int CHANGEUI = 1;
private Handler handler = new Handler()
{
@Override
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case SHOWINFO:
ShowInfo(MainActivity.this, msg.obj.toString());
break;
case CHANGEUI:
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void click(final View view)
{
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password))
{
Toast.makeText(this, "信息不可为空", Toast.LENGTH_LONG).show();
} else
{
new Thread()
{
@Override
public void run()
{
try
{
InputStream is = null;
// GET方式
if (view.getId() == R.id.btn_get)
{
is = getByHttpConnection(username, password);
} else if (view.getId() == R.id.btn_post)
{
is = postByHttpConnection(username, password);
} else if (view.getId() == R.id.btn_get_httpclient)
{
// HttpClient 方式
is = getByHttpClient(username, password);
} else if (view.getId() == R.id.btn_post_httpclient)
{
is = postByHttpClient(username, password);
}
final String res = StreamTools.StreamToString(is);
if (res != null)
{
// 不使用handler的另一种方式
// 这种方式也可以封装
runOnUiThread(new Runnable()
{
@Override
public void run()
{
ShowInfo(MainActivity.this, res);
}
});
} else
{
handler.sendMessage(getMsg(SHOWINFO, "失败"));
}
} catch (Exception e)
{
e.printStackTrace();
handler.sendMessage(getMsg(SHOWINFO, "获取失败"));
}
}
}.start();
}
}
private InputStream postByHttpConnection(final String username, final String password) throws MalformedURLException, IOException, ProtocolException
{
HttpURLConnection conn;
// POST方式
String path = "http://192.168.1.100:8080/ServletTest/Login";
URL post_url = new URL(path);
conn = (HttpURLConnection) post_url.openConnection();
conn.setRequestMethod("POST");
// 准备数据
String data = "username=" + username + "&password=" + password;
byte[] data_bytes = data.getBytes();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data_bytes.length + "");
// POST方式:浏览器将数据以流的方式写入服务器
conn.setDoOutput(true);// 允许向外部写入数据
OutputStream os = conn.getOutputStream();
os.write(data_bytes);
conn.setConnectTimeout(5000);
if (200 == conn.getResponseCode())
{
return conn.getInputStream();
}
return null;
}
private InputStream getByHttpConnection(final String username, final String password) throws UnsupportedEncodingException, MalformedURLException, IOException, ProtocolException
{
HttpURLConnection conn;
String path = "http://192.168.1.100:8080/ServletTest/Login" + "?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");
URL get_url = new URL(path);
conn = (HttpURLConnection) get_url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
return conn.getInputStream();
}
private InputStream getByHttpClient(final String username, final String password) throws Exception
{
String path = "http://192.168.1.100:8080/ServletTest/Login" + "?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8");
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
HttpResponse response = client.execute(httpGet);
if (200 == response.getStatusLine().getStatusCode())
{
return response.getEntity().getContent();
}
return null;
}
private InputStream postByHttpClient(final String username, final String password) throws Exception
{
String path = "http://192.168.1.100:8080/ServletTest/Login";
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(path);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse response = client.execute(httpPost);
if (200 == response.getStatusLine().getStatusCode())
{
return response.getEntity().getContent();
}
return null;
}
public Message getMsg(int what, Object obj)
{
Message msg = new Message();
msg.what = what;
msg.obj = obj;
return msg;
}
public void ShowInfo(Context context, String info)
{
Toast.makeText(context, info, Toast.LENGTH_SHORT).show();
}
}
package com.pas.htmlview.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamTools
{
public static String StreamToString(InputStream is)
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1)
{
baos.write(buffer, 0, len);
}
is.close();
baos.close();
byte[] res = baos.toByteArray();
String tem=new String(res);
return new String(res);
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
apache HttpClient API中的setConnectionTimeout,setSoTimeout和“ http.connection- manager.timeout”之间有什么区别
两者之间有什么区别(标记为评论):
MultiThreadedHttpConnectionManager connManag = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams managParams = connManag.getParams();
managParams.setConnectionTimeout(connectiontimeout); // 1
managParams.setSoTimeout(sotimeout); //2
HttpMethodBase baseMethod = null;
try {
HttpClient client = new HttpClient(connManag);
client.getParams().setParameter("http.connection-manager.timeout",poolTimeout); //3
baseMethod = new GetMethod(…);
int statusCode = client.executeMethod(…);
…
}
catch (ConnectTimeoutException cte ){
//Took too long to connect to remote host
}
catch (SocketTimeoutException ste){
//Remote host didn’t respond in time
}
catch (Exception se){
//Some other error occurred
}
finally {
if (baseMethod != null)
baseMethod.releaseConnection();
}
1. setConnectionTimeout
-如果它确定在建立连接之前的超时。
2. setSoTimeout
-如果确定两个连续数据包之间的不活动时间段或时间差,
那么下面的一个是做什么的:
3. "http.connection-manager.timeout"
Apache PoolingHttpClientConnectionManager引发非法状态异常
这是我的用法-
private static final PoolingHttpClientConnectionManager connPool;static { connPool = new PoolingHttpClientConnectionManager(); // Increase max total connection to 200 connPool.setMaxTotal(200);//configurable through app.properties // Increase default max connection per route to 50 connPool.setDefaultMaxPerRoute(20);//configurable through app.properties}CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connPool) .build();
另外,我在http GET周围放置了一个finally块-
finally { try { httpClient.close(); } catch (IOException e) { LOGGER.error(e.getMessage()); } }
这是我的堆栈跟踪-
java.lang.IllegalStateException: Connection pool shut down at org.apache.http.util.Asserts.check(Asserts.java:34) at org.apache.http.pool.AbstractConnPool.lease(AbstractConnPool.java:169) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection(PoolingHttpClientConnectionManager.java:217) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:157) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:194) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106) at com.A.B.C.CustomHttpClient.doGETAndValidate(CustomHttpClient.java:44) at com.A.B.C.SiteMonitorTask.monitorAndUpdateEndPoints(SiteMonitorTask.java:48) at com.A.B.C.SiteMonitorTask.run(SiteMonitorTask.java:37) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744)
我正在使用Quartz计划监视Http端点的工作。这是我的连接池配置
totalMaxHttpConn=200maxHttpConnPerRoute=20
Maven依赖..工件版本
httpclient 4.3.1httpcore 4.3.1
编辑 -好吧,通过不关闭finally块中的CloseableHttpClient,问题解决了。有人能说出为什么这样吗?
如果关闭客户端,为什么连接池会关闭?
是上面的closeablehttpclient是池的句柄,而不是单个conn
答案1
小编典典此行为是由于HC 4.3中的错误所致。它已在HC
4.4a1中修复。从4.4版本开始,CloseableHttpClient#close
仅在客户端独占时才应自动关闭连接池
关于不建议使用httpClient.getConnectionManager和-应该改用什么?的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于.conn.ManagedClientConnectionImpl@604ed9f0 java.net.ConnectException: Connection refused: connect、Android 网络提交数据 (HttpConnection HttpClient) POST GET 方式、apache HttpClient API中的setConnectionTimeout,setSoTimeout和“ http.connection- manager.timeout”之间有什么区别、Apache PoolingHttpClientConnectionManager引发非法状态异常等相关知识的信息别忘了在本站进行查找喔。
本文标签: