关于JAVA HttpClient链接超时问题

在项目中运用到了httpclient进行发送和接受请求,不知道为什么再走断点进行一步一步的查看代码的时候 走到这一步会出现链接超时,而如果不走断点却没有问题。
时间设置我设置成了30000000毫秒,走断点一直没有反应,等待遥遥无期,设置成30秒缺超时,请求大神帮忙解答疑问,是我eclipse的问题还是项目代码的问题?

1个回答

是异步调用的么?是不是后续代码在访问网页前就返回了。要具体看下你的代码

qq_32252023
qq_32252023 在用executeMethod这个方法的时候出现的问题。
大约 3 年之前 回复
qq_32252023
qq_32252023 int statusCode = http.executeMethod(postMethod);
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于页面跳转(链接超时的问题)
我现在有A,B,C三个page;rnA中输入的数据传送到B中检验,合格则输入sql;rn到了B中又会要求用户输入数据,在B中输入的数据传送到C中检验并插入数据;rn(我这么做是不想用户一次输入过多数据)rnrn现在在B和C中都有对先前页面输入的数据的检验,如果不合法则回退之先前页面重新输入rn我用的语句是rnecho " ";rn现在从B回退到A没问题,但是如果在B中输入错了,那么从C回退到B就会出现链接超时!rn我想问题就在于A的数据是经由B再传到C的。。。所以有这个问题;rnrn那我现在该怎么办呢,如果我在B页面刷新就会导致A的数据丢失。。。。。。
Volley框架的链接超时问题
自己做毕设 然后想用volley框架从后台取到数据 今天一早上全显示连接超时,很懵逼 求各路高手指点一二rn代码如下:rn[code=java]rnequestQueue requestQueue= Volley.newRequestQueue(this);//这里的this指的是Contextrn StringRequest request = new StringRequest("http://192.168.42.129:8080/Day2_6/JsonServlet", new Response.Listener() rn @Overridern public void onResponse(String response) rn Log.i("ceshi", "onResponse: success!"+response.toString());rn Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();rn rn , new Response.ErrorListener() rn @Overridern public void onErrorResponse(VolleyError error) rn Log.i("ceshi", "onResponse: fail!"+error.getMessage());rn rn );rn /*JsonObjectRequest request = new JsonObjectRequest("http://192.168.152.2:8080/Day2_6/JsonServlet",null,new Response.Listener() rn @Overridern public void onResponse(JSONObject response) rn Log.i("ceshi", "onResponse: success!"+response.toString());rn rn , new Response.ErrorListener() rn @Overridern public void onErrorResponse(VolleyError error) rn Log.i("ceshi", "onErrorResponse: fail!"+error.getMessage());rn rn );*/rn request.setRetryPolicy(new DefaultRetryPolicy(3*1000, 1, 1.0f));rn requestQueue.add(request);rn[/code]rn错误代码:rn[code=java]rnjava.net.ConnectException: failed to connect to /192.168.42.129 (port 8080) after 3000ms: connect failed: ENETUNREACH (Network is unreachable)rn[/code]rnrn我猜测应该是url的问题 可是我换了百度的网址(百度:为什么总是我躺枪。。。) 还是不行 rnPS: 联网权限 依赖 创建请求队列都有
GitHub下载链接超时问题
最近在搭建open-falcon的环境,其中有一步需要在GitHub上下载一个包,但是一直提示连接超时。将"https://github.com/open-falcon/of-release/releases/download/v0.1.0/open-falcon-v0.1.0.tar.gz"https改为http即可。...
sqlServer2000链接超时的问题
代码如下:rnpublic int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)rn rn using (SqlConnection conn = new SqlConnection(m_ConnectionString))rn rn //PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);rn conn.Open();rn SqlCommand cmd = new SqlCommand(cmdText, conn);rn cmd.CommandTimeout = 10;rn cmd.CommandType = cmdType;rn if (commandParameters != null)rn rn foreach (SqlParameter parm in commandParameters)rn rn cmd.Parameters.Add(parm);rn rn rn int val = cmd.ExecuteNonQuery();rn cmd.Parameters.Clear();rn return val;rn rn rnrn在往本地数据库写数据的时候,总是提示下面的错误:rnrnSystem.InvalidOperationException: 超时时间已到。超时时间已到,但是尚未从池中获取连接。出现这种情况可能是因为所有池连接均在使用,并且达到了最大池大小。rn 在 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)rn 在 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)rn 在 System.Data.SqlClient.SqlConnection.Open()rnrn请问各位高手,这是什么原因?谢谢!
一个链接超时的问题,求助下。
Request timed out. rnrn连接数据库时,页面报错。rnrnrn应该不少人遇到过,想知道下,大家都怎么处理的。
关于数据库链接超时问题
请问各位牛人,现在我数据库老是出现数据库链接超时问题,我把连接超时时间设为了600,也不能解决问题,我想问一下,有没有在连接快超时的时候,程序又自动进行连接,反正就是不能报数据库连接超时的错误
ora-12170链接超时问题
在一台linux服务器上安装了oracle10,服务器上访问没有问题,但客户端无法链接,提示ora-12170。rn我看监听器都是正常的啊:如下,我链接的是hmisrnLSNRCTL for Linux: Version 10.2.0.1.0 - Production on 23-SEP-2008 19:36:36rnrnCopyright (c) 1991, 2005, Oracle. All rights reserved.rnrnConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))rnSTATUS of the LISTENERrn------------------------rnAlias LISTENERrnVersion TNSLSNR for Linux: Version 10.2.0.1.0 - ProductionrnStart Date 23-SEP-2008 19:20:41rnUptime 0 days 0 hr. 15 min. 55 secrnTrace Level offrnSecurity ON: Local OS AuthenticationrnSNMP OFFrnListener Parameter File /home/oracle/product/10g/network/admin/listener.orarnListener Log File /home/oracle/product/10g/network/log/listener.logrnListening Endpoints Summary...rn (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))rn (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost.localdomain)(PORT=1521)))rnServices Summary...rnService "PLSExtProc" has 1 instance(s).rn Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...rnService "hmis" has 1 instance(s).rn Instance "hmis", status READY, has 1 handler(s) for this service...rnService "hmisXDB" has 1 instance(s).rn Instance "hmis", status READY, has 1 handler(s) for this service...rnService "hmis_XPT" has 1 instance(s).rn Instance "hmis", status READY, has 1 handler(s) for this service...rnThe command completed successfullyrn
关于数据库链接超时的问题
超时时间已到。在操作完成之前超时时间已过 主要是由于,执行存储过程耗时太长了。结果导致数据库命令对象超时,抛出异常。 目前能想到的办法是,在代码中找到命令对象比如SqlCommand对象,给CommandTimeOut属性赋一个比较大的值,我先把值赋到300,还会出错,赋0时,也是一样的出错,大家给我出个主意啊,还有什么办法能解决。
连接池链接超时
数据库连接池中的connection在八小时内没有被用到,则会自动断开连接,那么怎么处理数据库连接超时的问题?          我在自己写mybatis框架的时候,这样处理的:首先确保连接池中有指定数量的链接:将connection和创建时间System.currentTimeMillis()以键值对的形式存放在map集合中,用一个定时器,每隔1小时检查一下连接数目,数目大于指定个数,则从ma
java socket链接超时or拒绝链接
原因:ip或port错误            服务器自动防犯,拒绝链接            防火墙玩笑
java httpclient问题
用httpclient模拟登录一个网站,返回状态码(301或302等),我想不要处理返回状态码,直接用postMethod导向我要的页面,可以不考虑跳转吗?(不是说httpclient自动管理cookie,跳转应该可以忽略吧,哈哈,我的理解),求高手解释啊
HttpClient 的问题 在java 下编译出错。
我是新手,所以一边看代码,一边编译,加深理解,结果,一编译就报错,rn但又不是语法错误,求高手给解释一下。rnimport java.io.IOException;rnimport java.net.URI;rnimport java.net.URISyntaxException;rnrnimport org.apache.http.HttpResponse;rnimport org.apache.http.HttpStatus;rnimport org.apache.http.HttpVersion;rnimport org.apache.http.client.ClientProtocolException;rnimport org.apache.http.message.BasicHttpResponse;rnpublic class Client rn static URI uri;rn /**rn * @param argsrn * @throws IOException rn * @throws ClientProtocolException rn * @throws URISyntaxException rn */rn public static void main(String[] args) rn // TODO Auto-generated method stubrn HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,rn HttpStatus.SC_OK, "OK");rn System.out.println(response.getProtocolVersion());rn System.out.println(response.getStatusLine().getStatusCode());rn System.out.println(response.getStatusLine().getReasonPhrase());rn System.out.println(response.getStatusLine().toString());rnrnrn rnrnrnrnrnrnrnrnrnrnrnrnrnrnException in thread "main" java.lang.RuntimeException: Stub!rn at org.apache.http.message.AbstractHttpMessage.(AbstractHttpMessage.java:6)rn at org.apache.http.message.BasicHttpResponse.(BasicHttpResponse.java:8)rn at Client.main(Client.java:20)rn
java httpclient 代理问题
大家好!rn 我用Java httpClient写了一个用测试代理服务的程序,现在有一个问题,请大家帮我解决一下,谢谢!rn 我的代码是:rnpublic String getHtmlCodeByProxy (String proxyip, int proxyport, String type) throws Exception rn String str="";rn try rn //创建http客户端rn HttpClient httpClient = new HttpClient();rn httpClient.getHostConfiguration().setProxy(proxyip, proxyport);rn // 使用POST方法rn GetMethod getMethod = new GetMethod(Global.CLIENT_URL);rn int statusCode = httpClient.executeMethod(getMethod);rn if (statusCode == HttpStatus.SC_OK) rn str = getMethod.getResponseBodyAsString();rn rn catch (ConnectException e) rn e.printStackTrace();rn rn catch (IOException e) rn e.printStackTrace();rn rnrn错误信息是:rn2009-12-9 16:03:43 org.apache.commons.httpclient.HttpMethodDirector executeWithRrnetryrn信息: I/O exception (java.net.ConnectException) caught when processing request:rnConnection timed out: connectrn2009-12-9 16:03:43 org.apache.commons.httpclient.HttpMethodDirector executeWithRrnetryrn信息: Retrying requestrn我想问在代理无效的情况下,怎样捕获这个错误消息;谢谢!
关于httpclient模拟登录问题?
要求登录: http://xml2.weather.gov.hk/rn不过此网站并不是普通的登录页面,而是以弹出对话框的方式登录;rn[img=http://hi.csdn.net/attachment/201008/20/140639_12822889372TVk.jpg][/img]rn不知道怎样通过httpclient来登录rn[code=Java]rn private static final String LOGON_SITE = "xml2.weather.gov.hk"; rn private static final int LOGON_PORT = 80; rntryrn HttpClient client = new HttpClient(); rn client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); rn PostMethod post = new PostMethod("/V2/index.html"); rn//NameValuePair ie = new NameValuePair("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"); rn NameValuePair keepalive = new NameValuePair("Connection", "keep-alive"); rn NameValuePair username = new NameValuePair("username","用户不方便公布"); rn NameValuePair password = new NameValuePair("password", "秘密不方便公布");rn NameValuePair submit = new NameValuePair("submit", "yes");rn //不知道这里的表单参数要传哪些,并且他的参数是怎样定义的? rn post.setRequestBody(new NameValuePair[] username, password,submit); rn int iRes = client.executeMethod(post);rn System.out.println("iRes: "+iRes);rn}catchrn e.printStackTrace();rnrn[/code]
关于httpclient的问题
我的程序是想输出每个网页地址的响应状态,但是有一种状态好像是网络异常,提示信息下面标红的字体,我想不让红色的部分打印的出来,谢谢各位了!rnrn状态结果:4-HTTP/1.1 404 Not Foundrn状态结果:2-HTTP/1.1 404 Not Foundrn状态结果:1-HTTP/1.1 200 OKrn3 - error: [color=#0000FF]java.net.UnknownHostException:[/color] hc.apacwhe.orgrn[color=#FF0000]2012-8-9 10:48:26 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: I/O exception (java.net.SocketException) caught when processing request: Connection resetrn2012-8-9 10:48:27 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: Retrying requestrn2012-8-9 10:48:38 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: I/O exception (java.net.SocketException) caught when processing request: Connection resetrn2012-8-9 10:48:38 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: Retrying requestrn2012-8-9 10:48:50 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: I/O exception (java.net.SocketException) caught when processing request: Connection resetrn2012-8-9 10:48:50 org.apache.http.impl.client.DefaultRequestDirector tryExecutern信息: Retrying request[/color]rn5 - error: [color=#0000FF]java.net.SocketException:[/color] Connection resetrnrnrn============================================rn下面是我的程序:rnrnpublic class ClientMultiThreaded rn rn public static void main(String[] args) throws Exception rn rn HttpParams params = new BasicHttpParams(); rn rn SchemeRegistry schemeRegistry = new SchemeRegistry();rn schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); rn rn //创建一个与ThreadSafeClientConnManager HttpClient类。rn ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry); rn HttpClient httpClient = new DefaultHttpClient(cm); rn rn String[] urisToGet = rn "http://hc.apache.org/",rn "http://hc.apache.org/httpcodmponents-core/",rn "http://hc.apacwhe.org/httpcomponents-client/",rn "http://svn.apache.org/visewvc/httpcomponents/",rn "http://210.41.138.11:8080/opac/book/queryOut.jsp?kind=simple&type=number&word=7-80575-974-X"rn ;rn rn // create a thread for each URI rn GetThread[] threads = new GetThread[urisToGet.length];rn for (int i = 0; i < threads.length; i++) rn HttpGet httpget = new HttpGet(urisToGet[i]);rn threads[i] = new GetThread(httpClient, httpget, i + 1);rn rn rn rn // start the threads rn for (int j = 0; j < threads.length; j++) rn threads[j].start();rn rn rn // join the threads rn for (int j = 0; j < threads.length; j++) rn threads[j].join();rn rn rn httpClient.getConnectionManager().shutdown();rn rn rn rn /** rn * A thread that performs a GET. rn */ rn static class GetThread extends Thread rn rn private final HttpClient httpClient; rn private final BasicHttpContext context; rn private final HttpGet httpget; rn private final int id; rn rn public GetThread(HttpClient httpClient, HttpGet httpget, int id) rn this.httpClient = httpClient;rn this.context = new BasicHttpContext();rn this.httpget = httpget;rn this.id = id;rn rn rn /** rn * Executes the GetMethod and prints some status information. rn */ rn @Override rn public void run() rn rn //System.out.println(id + " - about to get something from :" + httpget.getURI()); rn rn try rn rn HttpResponse response = httpClient.execute(httpget); rn //HttpResponse statusCode = httpClient.execute(httpget);rn rn //System.out.println(id + " - about:" + httpget.getURI() + response.getStatusLine()); rn //int statusCode = httpClient.execute(httpget);rn rn System.out.println("状态结果:" + id + "-" + response.getStatusLine()); rn rn catch (IOException e) rn httpget.abort();rn rn System.out.println(id + " - error: " + e);rn finallyrn //释放连接rn httpget.releaseConnection();rn rn rn rnrnrn
关于HttpClient的问题
构造表单后,*.executeMethod(postMethod)执行post方法,返回成功登陆的htlm源码后,rn问题?rn此时如果执行GetMethod("请求资源URL")方法,请求资源被拒绝,说是没有登陆,可我上面已经post成功了,我想知道,在执行post以后,服务器肯定会把个人信息保存在session中,那么我之后的get要怎么样才能让服务器知道我是已登陆的用户呢?rnrn此问题还可以描述为,rn当用IE浏览器登陆以后,可以用浏览器下载文件,为什么用HttpClient不能下载,初步估计它们是两个不同的session,不知道对不对?
httpclient 关于date的问题
jsp上是使用
几个关于HttpClient的问题
当通过HttpClient大量访问同一个网站的时候会被拒绝,有什么好方法可以解决没有各位大神。rn另外URI不能够被识别的问题
关于httpclient和inputstream的问题
HttpClient httpClient = new HttpClient();rnGetMethod getMethod = new GetMethod(uri);rnInputStream responseBody = getMethod.getResponseBodyAsStream();rnbyte[] b= new byte[1024];rnwhile (responseBody.read(b) >= 0) rn System.out.println(new String(b));rnrnrn这段程序能把对应网页的代码打出来,但最后会少一小段,为什么?怎么才能把它完整输出?
关于HttpClient问题
HttpClientRequest 这个类是哪个jar包下面的?找了一大圈没找到
关于HttpClient下的Cookie问题
用HttpClient模拟登录网页,由于网站使用Cookie,抓Http头文件(登录后的),如下:rnget.setRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");rn// get.setRequestHeader("Referer","http://forum.51nb.com/index.php");rn// get.setRequestHeader("Cookie","cnzz02=9; rtime=4; ltime=1189649901828; cnzz_eid=21197383-http%3A//forum.51nb.com/index.php; cdb_cookietime=31536000; cdb_sid=uzxBlG; cdb_auth=oJQxyQbKQzH7E4HJAdUM9EdXA4Yh%2FqW%2Fga9D0eyIw7bYqsgX876hCXjfe8eGaXM");rn但是,我用getResponseHeaders()方法得到的Cookie只有db_sid=uzxBlG;而抓包的Cookie有很多项,如果只设置Cookie=db_sid=uzxBlG;是请求不到想要的页面,提示未登录,所以在请求的设置中配置:rnget.setRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");rn// get.setRequestHeader("Referer","http://forum.51nb.com/index.php");rn// get.setRequestHeader("Cookie","cnzz02=9; rtime=4; ltime=1189649901828; cnzz_eid=21197383-http%3A//forum.51nb.com/index.php; cdb_cookietime=31536000; cdb_sid=uzxBlG; cdb_auth=oJQxyQbKQzH7E4HJAdUM9EdXA4Yh%2FqW%2Fga9D0eyIw7bYqsgX876hCXjfe8eGaXM");rn我的问题是:头文件里的cookie里那么多项是什么意思,我该如何得到它们?谢谢赐教!
关于httpclient连接池的问题
我有一个项目需要下载各种图片,图片来自不通的网站。rn请问这种应用连接池有用吗?
关于 HttpClient的复用问题
https://segmentfault.com/q/1010000013418398
请教关于httpclient的问题
我使用的jdk为1.4.2_16,应该下载httpclient的哪个版本??我下了4.2,结果在新建的java工程中什么程序也不能运行,一直提示could not find the main class。rn请高手指点一下,因为第一次使用httpclient,能不能给讲一讲具体使用环境怎么配置?我用的是myeclipse8.5rn谢谢!
关于apache httpclient的问题
请教各位大神,怎么给get请求添加请求头的信息,我这里老是报错[img=https://img-bbs.csdn.net/upload/201512/02/1449054229_590422.png][/img]
关于httpclient的问题 急!!!
我需要实现这样一个功能,同过本地的swing程序将文件上传到php服务器上,上传功能是通过apache的httpclient实现的.现在的问题是在jBuilder2005中可以实现,但是压成exe就不行了,该压的包也压了,classpath中也指定了httpclient,但就是上传不了,我怀疑是配置问题,请各位大侠指教.
关于HTTPCLIENT超时的问题
各位大侠好,最近碰到一个问题,在使用httpclient的post方法时,遇到了超时错误,如下rn169318787-12-16 13:57:36 - I/O exception (java.net.ConnectException) caught when processing request: Connection timed outrn169318899:12-16 13:57:36 - Retrying requestrn根据httpclient的默认策略,是会重试三次,但是三次以后就直接抛出了ConnectException这个异常,网上说超时异常是可以通过IOException来捕获的,但是这里实际上该异常没有被捕获,求解,程序如下rnpublic static byte[] getBody(String url, String parms) rn byte[] body = null;rn // 构造HttpClient的实例rn HttpClient httpClient = new HttpClient();rn // 创建GET方法的实例rn PostMethod postMethod = new PostMethod(url);rn postMethod.setRequestHeader("Content-type", "text/xml; charset=GBK");rn // 将表单的值放入postMethod中rn try rn postMethod.setRequestEntity(new StringRequestEntity(parms,rn "text/xml; charset=GBK", null));rn catch (UnsupportedEncodingException e1) rn // TODO Auto-generated catch blockrn e1.printStackTrace();rn rn // 执行postMethodrn int statusCode;rn try rn statusCode = httpClient.executeMethod(postMethod);rnrn // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发rn // 301或者302rn if (statusCode == HttpStatus.SC_MOVED_PERMANENTLYrn || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) rn // 从头中取出转向的地址rn Header locationHeader = postMethodrn .getResponseHeader("location");rn String location = null;rn if (locationHeader != null) rn location = locationHeader.getValue();rn System.outrn .println("The page was redirected to:" + location);rn else rn System.err.println("Location field value is null.");rn rn rn body = postMethod.getResponseBody();rn catch (HttpException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn catch (IOException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn finally rn // 释放连接rn postMethod.releaseConnection();rn rn return body;rn
HttpClient关于Cookie的问题
我用HttpClient获取到的Cookie只有很少的信息,而我用HttpWatch抓取到的Cookie却比用HttpClient获取到的多很多,因此也无法模拟登录想要的那个站点了。请问,为什么会出现这种情况,怎么解决问题,谢谢?
关于httpclient的https问题
请教一个问题rn使用HttpsURLConnection这个类可以直接访问https的网站,也不需要证书rn[code=Java]private void testIt1()rn URL url;rn try rn url = new URL("https://www.alipay.com/index.html");rn HttpsURLConnection con = (HttpsURLConnection)url.openConnection();rn //dump all the contentrn if(con!=null)rn System.out.println("****** Content of the URL ********");rn BufferedReader br =new BufferedReader(new InputStreamReader(con.getInputStream()));rn String input;rn while ((input = br.readLine()) != null)rn System.out.println(input);rn rn br.close();rn rn catch (Exception e) rn e.printStackTrace();rn rn [/code]rn换成httpclient怎么写rn例如:我打开支付宝,在浏览器里输入网址即可,换成httpclient怎么写??rn谢谢!rn
关于HttpClient的问题,如何使用HttpClient重定向?
nn```n /*n * HttpRequestProxy.javan *n * Created on November 3, 2008, 9:53 AMn */nnnimport java.io.BufferedReader;nimport java.io.IOException;nimport java.io.InputStream;nimport java.io.InputStreamReader;nimport java.util.HashMap;nimport java.util.Iterator;nimport java.util.Map;nimport java.util.Set;nnimport org.apache.commons.httpclient.Header;nimport org.apache.commons.httpclient.HttpClient;nimport org.apache.commons.httpclient.HttpException;nimport org.apache.commons.httpclient.HttpMethod;nimport org.apache.commons.httpclient.NameValuePair;nimport org.apache.commons.httpclient.SimpleHttpConnectionManager;nimport org.apache.commons.httpclient.methods.GetMethod;nimport org.apache.commons.httpclient.methods.PostMethod;nnnpublic class HttpRequestProxy n // 超时间隔n private static int connectTimeOut = 60000;n // 让connectionmanager管理httpclientconnection时是否关闭连接n private static boolean alwaysClose = false;n // 返回数据编码格式n private String encoding = "UTF-8";nn private final HttpClient client = new HttpClient();nn public HttpClient getHttpClient() n return client;n n /**n * 用法: HttpRequestProxy hrp = new HttpRequestProxy();n * hrp.doRequest("http://www.163.com",null,null,"gbk");n * n * @param urln * 请求的资源URLn * @param postDatan * POST请求时form表单封装的数据 没有时传nulln * @param headern * request请求时附带的头信息(header) 没有时传nulln * @param encodingn * response返回的信息编码格式 没有时传nulln * @return response返回的文本数据n * @throws CustomExceptionn */n public String doRequest(String url, Map postData, Map header, String encoding) throws Exception n String responseString = null;n // 头部请求信息n Header[] headers = null;n if (header != null) n Set entrySet = header.entrySet();n int dataLength = entrySet.size();n headers = new Header[dataLength];n int i = 0;n for (Iterator itor = entrySet.iterator(); itor.hasNext();) n Map.Entry entry = (Map.Entry) itor.next();n headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString());n n n n // post方式n if (postData != null) n PostMethod postRequest = new PostMethod(url.trim());n if (headers != null) n for (int i = 0; i < headers.length; i++) n postRequest.setRequestHeader(headers[i]);n n n Set entrySet = postData.entrySet();n int dataLength = entrySet.size();n NameValuePair[] params = new NameValuePair[dataLength];n int i = 0;n for (Iterator itor = entrySet.iterator(); itor.hasNext();) n Map.Entry entry = (Map.Entry) itor.next();n params[i++] = new NameValuePair(entry.getKey().toString(), entry.getValue().toString());n n postRequest.setRequestBody(params);n try n responseString = this.executeMethod(postRequest, encoding);n catch (Exception e) n throw e;n finally n postRequest.releaseConnection();n n n return responseString;n nn private String executeMethod(HttpMethod request, String encoding) throws Exception n String responseContent = null;n InputStream responseStream = null;n BufferedReader rd = null;n try n this.getHttpClient().executeMethod(request);n if (encoding != null) n responseStream = request.getResponseBodyAsStream();n rd = new BufferedReader(new InputStreamReader(responseStream, encoding));n String tempLine = rd.readLine();n StringBuffer tempStr = new StringBuffer();n String crlf = System.getProperty("line.separator");n while (tempLine != null) n tempStr.append(tempLine);n tempStr.append(crlf);n tempLine = rd.readLine();n n responseContent = tempStr.toString();n elsen responseContent = request.getResponseBodyAsString();nn Header locationHeader = request.getResponseHeader("location");n // 返回代码为302,301时,表示页面己经重定向,则重新请求location的url,这在n // 一些登录授权取cookie时很重要n if (locationHeader != null) n String redirectUrl = locationHeader.getValue();n this.doRequest(redirectUrl, null, null, null);n n catch (HttpException e) n throw new Exception(e.getMessage());n catch (IOException e) n throw new Exception(e.getMessage());nn finally n if (rd != null)n try n rd.close();n catch (IOException e) n throw new Exception(e.getMessage());n n if (responseStream != null)n try n responseStream.close();n catch (IOException e) n throw new Exception(e.getMessage());nn n n return responseContent;n nn /**n * 特殊请求数据,这样的请求往往会出现redirect本身而出现递归死循环重定向 所以单独写成一个请求方法n * 比如现在请求的url为:http://localhost:8080/demo/index.jsp 返回代码为302n * 头部信息中location值为:http://localhost:8083/demo/index.jspn * 这时httpclient认为进入递归死循环重定向,抛出CircularRedirectException异常n * n * @param urln * @returnn * @throws CustomExceptionn */n public String doSpecialRequest(String url, int count, String encoding) throws Exception n String str = null;n InputStream responseStream = null;n BufferedReader rd = null;n GetMethod getRequest = new GetMethod(url);n // 关闭httpclient自动重定向动能n getRequest.setFollowRedirects(false);n try nn this.client.executeMethod(getRequest);n Header header = getRequest.getResponseHeader("location");n if (header != null) n // 请求重定向后的URL,count同时加1n this.doSpecialRequest(header.getValue(), count + 1, encoding);n n // 这里用count作为标志位,当count为0时才返回请求的URL文本,n // 这样就可以忽略所有的递归重定向时返回文本流操作,提高性能n if (count == 0) n getRequest = new GetMethod(url);n getRequest.setFollowRedirects(false);n this.client.executeMethod(getRequest);n responseStream = getRequest.getResponseBodyAsStream();n rd = new BufferedReader(new InputStreamReader(responseStream, encoding));n String tempLine = rd.readLine();n StringBuffer tempStr = new StringBuffer();n String crlf = System.getProperty("line.separator");n while (tempLine != null) n tempStr.append(tempLine);n tempStr.append(crlf);n tempLine = rd.readLine();n n str = tempStr.toString();n nn catch (HttpException e) n throw new Exception(e.getMessage());n catch (IOException e) n throw new Exception(e.getMessage());n finally n getRequest.releaseConnection();n if (rd != null)n try n rd.close();n catch (IOException e) n throw new Exception(e.getMessage());n n if (responseStream != null)n try n responseStream.close();n catch (IOException e) n throw new Exception(e.getMessage());n n n return str;n nn public static void main(String[] args) throws Exception nn HttpRequestProxy hrp = new HttpRequestProxy();n Map date = new HashMap();n date.put("jyidApplet", "1");n date.put("codeNumApplet", "1");n date.put("jymxIdApplet", "447");n date.put("patientIdApplet", "1118");n String str = hrp.doRequest("http://127.0.0.1:8080/lis/mz/addTM",date, null, null);n System.out.println(str);n n nnnn```nn
关于httpclient的一个问题
[code=Java]import org.apache.commons.httpclient.Cookie; rnimport org.apache.commons.httpclient.HttpClient; rnimport org.apache.commons.httpclient.NameValuePair; rnimport org.apache.commons.httpclient.methods.GetMethod; rnimport org.apache.commons.httpclient.methods.PostMethod; rnimport org.apache.commons.httpclient.params.HttpMethodParams;rnimport org.apache.commons.httpclient.Header;rnimport org.apache.commons.httpclient.HttpMethod;rnrnpublic class TestOfPost rnrn private static final String LOGON_SITE = "222.195.226.80"; rn private static final int LOGON_PORT = 8080; rn private static final String CONTENT_CHARSET = "GBK";rnrn public static void main(String[] args) throws Exceptionrn HttpClient client = new HttpClient();rn NameValuePair[] bodyData = rn new NameValuePair("E", "%28Keyword_C%3D%28%BB%FA%C6%F7%D1%A7%CF%B0%29%2BTitle_C%3D%28%BB%FA%C6%F7%D1%A7%CF%B0%29%29"), rn new NameValuePair("S", "1"),rn new NameValuePair("N","20"),rn new NameValuePair("C","0"),rn new NameValuePair("H","%CC%E2%C3%FB%BB%F2%B9%D8%BC%FC%B4%CA%3D%BB%FA%C6%F7%D1%A7%CF%B0*%C4%EA%3D1989-2009"),rn new NameValuePair("M",""),rn new NameValuePair("KM",""), rn new NameValuePair("P","1"),rn new NameValuePair("CSID","%7B7C68141A-0DA1-40A4-8027-8C96AE5A2C5F%7D") rn ;rn rn client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET); rn client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);rn rn PostMethod pmlogin = new PostMethod("/loginn_ybjs.asp");rn pmlogin.addRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QQDownload 584; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)");rnrn client.executeMethod(pmlogin);rn Cookie[] cookiess = client.getState().getCookies();rn client.getState().addCookies(cookiess); rn System.out.println ("***************************************登录Response*****************************************");rn System.out.println (pmlogin.getResponseBodyAsString());rn rn rn PostMethod pml = new PostMethod("/CSTJ/Sear.dll?SearchZk"); rn pml.setRequestBody(bodyData);rn pml.addRequestHeader("Accept","application/x-shockwave-flash, image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*");rn pml.addRequestHeader("Referer","http://222.195.226.80:8080/loginn_ybjs.asp"); rn pml.addRequestHeader("Accept-Language","zh-cn");rn pml.addRequestHeader("Content-Type","application/x-www-form-urlencoded"); rn pml.addRequestHeader("Accept-Encoding","gzip, deflate");rn pml.addRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QQDownload 584; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)");rn //pml.addRequestHeader("url", "/CSTJ/Sear.dll?SearchZK");rn pml.addRequestHeader("Host","222.195.226.80:8080");rn pml.addRequestHeader("Content-Length","250");rn pml.addRequestHeader("Connection","Keep-Alive");rn pml.addRequestHeader("Pragma","no-cache");rn client.executeMethod(pml);rn System.out.println ("***************************************查询Post-response*****************************************");rn System.out.println (pml.getResponseBodyAsString()); rnrn pml.releaseConnection(); rn rn rnrn[/code]rn输出结果为:rn[code=#]--------------------Configuration: --------------------rn***************************************登录Response*****************************************rnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn***************************************查询Post-response*****************************************rn2009-10-4 13:01:29 org.apache.commons.httpclient.HttpMethodBase getResponseBodyrn警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.rn 无效请求 客户端发出一个服务器无法处理的请求. 请求: SearchZkrnrnrnProcess completed.[/code]
HttpClient httpclient = new HttpClient();关于这个
HttpClient httpclient = new HttpClient(); rn PostMethod post = new PostMethod(server); rn String info = null; rn System.out.println("post data---> "+obj);rn RequestEntity entity = new StringRequestEntity(obj.toString(), "text/xml","utf-8"); rn post.setRequestEntity(entity); rn httpclient.executeMethod(post); rn int code = post.getStatusCode(); rn if (code == HttpStatus.SC_OK) rn info = new String(post.getResponseBodyAsString());rn rn result =JSONObject.fromObject(info);rn来个大牛帮我翻译下!!!!!我不是很清楚这段话是什么意思!!!!求大牛解释
如何设置数据链接超时的问题
asp.net与sql 2000,如何设置与数据库链接超时的问题,在哪里设,有谁知道的?
java???HttpClient????
我使用MyEclipse把httpclient的两个jar文件httpcore-4.0-beta3,httpcore-nio-4.0-beta3加到已经加到用户的库中,引用但是它说找不到rnpackage com.test;rnimport java.io.IOException;rnimport [color=#FF0000]org.apache.commons.[/color]httpclient.*;rnimport o[color=#FF0000]rg.apache.commons.httpclient.[/color]methods.GetMethod;rnimport [color=#FF0000]org.apache.commons.httpclient.[/color]params.HttpMethodParams;rnrnimport sun.net.www.http.HttpClient;rnpublic class GetSamplern public static void main(String[] args) rn //构造HttpClient的实例rn HttpClient httpClient = new HttpClient();rn //创建GET方法的实例rn GetMethod getMethod = new GetMethod("http://www.ibm.com");rn //使用系统提供的默认的恢复策略rn getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,rn new DefaultHttpMethodRetryHandler());rn try rn //执行getMethodrn int statusCode = httpClient.executeMethod(getMethod);rn if (statusCode != HttpStatus.SC_OK) rn System.err.println("Method failed: "rn + getMethod.getStatusLine());rn rn //读取内容 rn byte[] responseBody = getMethod.getResponseBody();rn //处理内容rn System.out.println(new String(responseBody));rn catch (HttpException e) rn //发生致命的异常,可能是协议不对或者返回的内容有问题rn System.out.println("Please check your provided http address!");rn e.printStackTrace();rn catch (IOException e) rn //发生网络异常rn e.printStackTrace();rn finally rn //释放连接rn getMethod.releaseConnection();rn rn rnrnrn加红的地方,找不到,但是我已经引入了,不知道为什么,请大家看看,谢谢了。rnrn
java httpclient
用java实现httpclient请求的类
关于httpClient
我用IE访问如下地址并且在客户端已经生成了cookie的,但是我用httpClient访问,服务器就是读取不到这个已经生成的cookie,这个是怎么回事呀?rn[code=Java]rnrn//构造HttpClient的实例rn HttpClient httpClient = new HttpClient();rn //创建GET方法的实例rn GetMethod getMethod = new GetMethod("http://www.ibm.com");rn //使用系统提供的默认的恢复策略rn getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,rn new DefaultHttpMethodRetryHandler());rn try rn //执行getMethodrn int statusCode = httpClient.executeMethod(getMethod);rn if (statusCode != HttpStatus.SC_OK) rn System.err.println("Method failed: "rn + getMethod.getStatusLine());rn rn //读取内容 rn byte[] responseBody = getMethod.getResponseBody();rn //处理内容rn System.out.println(new String(responseBody));rn catch (HttpException e) rn //发生致命的异常,可能是协议不对或者返回的内容有问题rn System.out.println("Please check your provided http address!");rn e.printStackTrace();rn catch (IOException e) rn //发生网络异常rn e.printStackTrace();rn finally rn //释放连接rn getMethod.releaseConnection();rn rnrnrn[/code]rnrnrnrn难道Cookie还得自己维护,httpClient不负责维护?请达人指教一二。
关于HttpClient
为什么访问外网就不行呢,抛出异常,说是连接被拒绝,多谢各位
问一个关于httpclient 的问题。。。
为什么返回html是登陆页面,完全没有发出去的感觉rn代码:rnHttpPost post = new HttpPost("http://www.homevv.com/vvshopNeedLogin.jhtml?");rnList nvps = new ArrayList();rnnvps.add(new BasicNameValuePair("loginId", "xxxxxx")); rnnvps.add(new BasicNameValuePair("password", "xxxxxx")); rnnvps.add(new BasicNameValuePair("rememberMe", "true")); rnpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));rnHttpResponse response = httpclient.execute(post);rnString strResult=EntityUtils.toString(response.getEntity());rnSystem.out.println(strResult);rnrn还有最新的4.3X怎么设置带用户名密码的代理的公司走的外线之前的代码不能用了!rnhttpClient.getCredentialsProvider().setCredentials 这个方法不见了!
关于httpclient模拟post的问题
aspx页面的一个form 通过 点击 登录 按钮 获得一个在text输入的账号和密码后,调用on_click事件来验证,再返回登录结果。rn我现在想 如何才能激发这个on_click事件 多谢了rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rnrn rnrnrn下面是button1_Click事件:rnprotected void Button1_Click(object sender, EventArgs e)rn rnrn if (this.nickname.Text == "" || this.password.Text == "")rn rn Common.ShowMsg("请填写完整!");rn rn elsern rnrn string nick = this.nickname.Text;rn string pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(this.password.Text, "MD5");rn Student s = this.sbll.loginStudent(nick, pwd);rn if (s != null)rn rn Session.Add("student", s);rn Response.Redirect("Student/Default.html");rn rn elsern rn Response.Write(" ");rn // Response.Redirect("default.aspx");rn rnrn rn
关于httpclient抓取数据问题
请问各位大大,org.apache.http.conn.HttpHostConnectException: Connection to ………… refused,出现这种问题应该怎么解决啊
相关热词 c# 标准差 计算 c#siki第五季 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池