关于commons.httpclient.HttpClient和http.client.HttpClient的区别!!!

这两个包都是apache提供网络请求的, 请问具体区别。。。

很纠结,不知道用哪个最合适,org.apache.http.client.HttpClient但我觉得这个包的更专业,不确定,希望大家回答下。

标题太长 我去掉了一些

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
日志是INFO级别 httpclient 控制台还是打印很多信息。怎么关闭
[14/01/03 09:42:53:942][org.apache.commons.httpclient.HttpClient-<clinit>] Java version: 1.6.0_37 [14/01/03 09:42:53:973][org.apache.commons.httpclient.HttpClient-<clinit>] Java vendor: Sun Microsystems Inc. [14/01/03 09:42:53:973][org.apache.commons.httpclient.HttpClient-<clinit>] Java class path: XMLSignatureFactory; [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "3" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "3" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\r]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\n]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "{"infocode":"000000","infotext":"","result":"true"}" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\r]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\n]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "0" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\r]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\n]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\r]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\n]" [14/01/03 09:42:54:286][org.apache.commons.httpclient.Wire-wire] << "[\r][\n]" 怎么设置可以不让他打印这些
java.net.ConnectException 帮我看看这个错!
2009-10-21 15:31:04 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect 2009-10-21 15:31:04 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:79) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:121) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324) at com.icbc.SSL.SSLSendAndRec.main(SSLSendAndRec.java:57) [b]问题补充:[/b] client.getHostConfiguration().setProxy() 我设置了代理的
线程一直处于RUNNABLE,也没有发现阻塞或是死锁的情况?
我写的是一个频繁访问网络的爬虫,启了20个线程; 但是老实跑了一段时间,线程全部处于RUNNABLE状态了; 网络使用的是httpclient3.1; 我把threaddump给放到下面: ``` "Thread-19" #30 prio=5 os_prio=0 tid=0x0000000059b3d000 nid=0xcb4 runnable [0x000000005ba1e000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) at java.io.BufferedInputStream.read(BufferedInputStream.java:265) - locked <0x0000000086f05c90> (a java.io.BufferedInputStream) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.uzons.domain.search.v2.searcher.EBChecker.validate(EBChecker.java:34) at com.uzons.domain.search.v2.taskscheduler.DomainJob.exec(DomainJob.java:28) at com.uzons.domain.search.v2.taskscheduler.DomainScheduler.execute(DomainScheduler.java:110) at com.uzons.domain.search.v2.taskscheduler.DomainScheduler.run(DomainScheduler.java:92) Locked ownable synchronizers: - None ```
两种httpClient区别
org.apache.commons.httpclient.HttpClient 与 org.apache.http.client.HttpClient区别 最近在看httpclient相关的代码 但发现两个包里同样的类名 网上资料是commons这个包下的比较多 请教下这两个类的具体区别
java使用httpclient向百度的收录入口提交URL报 403错误
package com.galaxy.promotion.baidu; import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class Test { public static void main(String[] args) throws HttpException, IOException { HttpClient httpclient = new HttpClient(); // 创建post方法实例 PostMethod postMethod = new PostMethod("http://zhanzhang.baidu.com/linksubmit/urlsubmit"); // 填入各个表单域的值 NameValuePair[] data = { new NameValuePair("url", "www.example.com") }; // 将表单的值放入到post方法中 postMethod.setRequestBody(data); // 执行post方法 int statusCode = httpclient.executeMethod(postMethod); System.out.println(statusCode); System.out.println(postMethod.getStatusLine()); } }
java爬虫求助,为什么报异常了,怎么解决
package org; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; public class RetrivePage { private static HttpClient httpClient = new HttpClient(); // 设置代理服务器 static { // 设置代理服务器的IP地址和端口 httpClient.getHostConfiguration().setProxy("172.17.18.84", 8080); } public static boolean downloadPage(String path) throws HttpException, IOException { InputStream input = null; OutputStream output = null; // 得到post方法 PostMethod postMethod = new PostMethod(path); // 设置post方法的参数 /*NameValuePair[] postData = new NameValuePair[2]; postData[0] = new NameValuePair("name","lietu"); postData[1] = new NameValuePair("password","*****"); postMethod.addParameters(postData); */ // 执行,返回状态码 int statusCode = httpClient.executeMethod(postMethod); // 针对状态码进行处理 (简单起见,只处理返回值为200的状态码) if (statusCode == HttpStatus.SC_OK) { input = postMethod.getResponseBodyAsStream(); //得到文件名 String filename = path.substring(path.lastIndexOf('/')+1); //获得文件输出流 output = new FileOutputStream(filename); //输出到文件 int tempByte = -1; while((tempByte=input.read())>0){ output.write(tempByte); } //关闭输入输出流 if(input!=null){ input.close(); } if(output!=null){ output.close(); } return true; } //若需要转向,则进行转向操作 if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) { //读取新的URL地址 Header header = postMethod.getResponseHeader("location"); if(header!=null){ String newUrl = header.getValue(); if(newUrl==null||newUrl.equals("")){ newUrl="/"; //使用post转向 PostMethod redirect = new PostMethod(newUrl); //发送请求,做进一步处理。。。。。 } } } return false; } /** * 测试代码 */ public static void main(String[] args) { // 抓取lietu首页,输出 try { RetrivePage.downloadPage("http://www.lietu.com"); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 下面是异常 八月 27, 2016 4:16:28 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect 八月 27, 2016 4:16:28 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request 八月 27, 2016 4:16:49 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect 八月 27, 2016 4:16:49 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request 八月 27, 2016 4:17:10 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect 八月 27, 2016 4:17:10 下午 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request java.net.ConnectException: Connection timed out: 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 java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:79) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:121) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324) at org.RetrivePage.downloadPage(RetrivePage.java:37) at org.RetrivePage.main(RetrivePage.java:82)
HttpClient超时没有控制住
项目中由于需要调用第三方接口,由于第三方接口不可控,我们设置的有超时时间 PostMethod post = new PostMethod(url); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); client.getParams().setConnectionManagerTimeout(connectionTimeOut); client.getParams().setSoTimeout(soTimeOut); post.setRequestBody(parameters); client.executeMethod(post); InputStream responseBody = post.getResponseBodyAsStream(); InputStreamReader in = new InputStreamReader(responseBody, "utf-8"); BufferedReader br = new BufferedReader(in); StringBuffer rets = new StringBuffer(); String inputLine = ""; while ((inputLine = br.readLine()) != null){ rets.append(inputLine); } in.close(); String data = rets.toString().trim(); return data; 正常情况下能控制住,没有问题,但是昨天发生没有控住的情况,第三方表示升级网络改了hosts地址, 请问大神帮忙忽略网络问题从程序的角度分析为什么会没控制住,谢谢。
寻求HttpClient无法写Cookie的解决方法
问题描述: 公司申请了一个超短域名,假设改域名为 a.cn,有多个二级域名 比如 www.a.cn; file.a.cn;这些二级域名都有一个共同的功能, 就是要写cookie,而且这个cookie要在a.cn内共享。根据短域名写cookie的可行性,只能把写Cookie的功能统一交给a.cn这台服务器来执行才可以写成功。所以我现在如果要在www.a.cn服务器上写cookie(可供a.cn共享的Cookie),就只能借助HttpClient 在a.cn服务器上有一个Servlet,用来负责写Cookie,www.a.cn这台服务器上的应用程序借助HttpClient调用a.cn上的Servlet 一切执行都没有问题,但是就是Cookie无法写入文件中。如果在IE中直接调用那个Servlet,这可以把Cookie成功写入文件。 假如Servlet的完整请求地址为 http://a.cn/servlet a.an 服务器负责写Cookie的代码如下 [code="java"] public class CookieServlet extends HttpServlet { public CookieServlet() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("CookieName", "haha"); cookie.setMaxAge(100000); cookie.setPath("/"); //这个不需要设置 //cookie.setDomain("a.cn"); response.addCookie(cookie); } public void init() throws ServletException { } } [/code] www.a.cn的请求代码如下 [code="java"] public class Test { public static void main(String args[]) { String cookieUrl = "http://a.cn/servlet"; String result = HttpUtils.executeGetMethod(cookieUrl); //其余代码省略,这里执行完后,并没有得到理想的结果。cookie没有写成功,如果 //在IE浏览器中执行 执行http://a.cn/servlet ,则可以成功写cookie } [/code] [code="java"] import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class HttpUtils { private static MultiThreadedHttpConnectionManager httpManager; private static final Log log = LogFactory.getLog(HttpUtils.class); public static HttpConnectionManager getHttpManager() { if (httpManager == null) { httpManager = new MultiThreadedHttpConnectionManager(); httpManager.getParams().setConnectionTimeout(3000); } return httpManager; } public static HttpClient createHttpClient() { HttpClient client = new HttpClient(getHttpManager()); return client; } public static String executeGetMethod(String url) { HttpMethod method = new GetMethod(url.toString()); return getHttpResult(method); } public static String executePostMethod(String url, Map<String, String> map) { PostMethod method = new InnerPostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); if (map == null || map.size() == 0) { throw new IllegalArgumentException("map must be not null"); } NameValuePair[] data = new NameValuePair[map.size()]; Set<Map.Entry<String, String>> set = map.entrySet(); Iterator<Map.Entry<String, String>> it = set.iterator(); int i = 0; while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); data[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } method.setRequestBody(data); return getHttpResult(method); } private static String getHttpResult(HttpMethod method) { InputStream is = null; try { HttpClient client = HttpUtils.createHttpClient(); int stat = client.executeMethod(method); if (stat != HttpStatus.SC_OK) { return null; } is = method.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8")); StringBuilder builder = new StringBuilder(); String tmp = null; while ((tmp = reader.readLine()) != null) { builder.append(tmp); } // Cookie cks[] = client.getState().getCookies(); // if (cks != null) { // for (Cookie c : cks) { // System.out.println(c.getName()+"\t"+c.getValue()); // } // } return builder.toString(); } catch (HttpException e) { return null; } catch (IOException e) { return null; } finally { method.releaseConnection(); try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } static class InnerPostMethod extends PostMethod { public InnerPostMethod(String url) { super(url); } @Override protected String getContentCharSet(Header contentheader) { return "UTF-8"; } } } [/code] 希望有遇到过类似问题的高手,给予帮助,谢谢
模拟登录教务在线,为什么进去的不是登录后的界面,而是登录前的界面,求大神帮忙,毕业论文需要
package loginApp; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class ImitateLogin { public static void main(String[] args) { String userName = "1307012027"; // 本人学号 String password = "360731*********"; // 本人密码 String loginUrl = "http://jwc.jxnu.edu.cn/Default_Login.aspx?preurl="; String dataUrl = "http://jwc.jxnu.edu.cn"; HttpClientLogin(userName, password, loginUrl, dataUrl); } private static void HttpClientLogin(String userName, String password, String loginUrl, String dataUrl) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); PostMethod postMethod = new PostMethod(loginUrl); NameValuePair[] postData = { new NameValuePair("StuNum", userName), new NameValuePair("Password", password) }; postMethod.setRequestBody(postData); try { httpClient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY); httpClient.executeMethod(postMethod); Cookie[] cookies = httpClient.getState().getCookies(); StringBuffer stringBuffer = new StringBuffer(); for (Cookie c : cookies) { stringBuffer.append(c.toString() + ";"); } GetMethod getMethod = new GetMethod(dataUrl); getMethod.setRequestHeader("Cookie", stringBuffer.toString()); postMethod.setRequestHeader("Host", "http://jwc.jxnu.edu.cn"); postMethod.setRequestHeader("Referer", "http://jwc.jxnu.edu.cn/Default_Login.aspx?preurl="); postMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"); httpClient.executeMethod(getMethod); String result = getMethod.getResponseBodyAsString(); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } }
java.net.UnknownHostException:
java.net.UnknownHostException at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:86) at org.apache.commons.httpclient.HttpConnection$1.doit(HttpConnection.java:660) at org.apache.commons.httpclient.HttpConnection$SocketTask.run(HttpConnection.java:1291) at java.lang.Thread.run(Unknown Source) 改了jnlp url指向的域名,结果运行客户端的时候还是指向老的域名。 求大神解疑惑
调用OAuth4Code 出现weibo4j.model.WeiboException: Connection reset错误
执行OAuth4Code 跳转到配置文件中定义的redirect_URI , 从浏览器中拷贝code在控制台中黏贴,回车,代码继续执行到 oauth.getAccessTokenByCode(code); 报下列异常 Hit enter when it's done.[Enter]:633579c984915e30f8127d9b833b4b56 1 INFO [2013-08-02 11:12:06] code: 633579c984915e30f8127d9b833b4b56 6 DEBUG [2013-08-02 11:12:06] Request: 6 DEBUG [2013-08-02 11:12:06] POSThttps://api.weibo.com/oauth2/access_token 346 INFO [2013-08-02 11:12:07] I/O exception (java.net.SocketException) caught when processing request: Connection reset 346 INFO [2013-08-02 11:12:07] Retrying request 364 INFO [2013-08-02 11:12:07] I/O exception (java.net.SocketException) caught when processing request: Connection reset 364 INFO [2013-08-02 11:12:07] Retrying request 382 INFO [2013-08-02 11:12:07] I/O exception (java.net.SocketException) caught when processing request: Connection reset 382 INFO [2013-08-02 11:12:07] Retrying request weibo4j.model.WeiboException: Connection reset at weibo4j.http.HttpClient.httpRequest(HttpClient.java:422) at weibo4j.http.HttpClient.post(HttpClient.java:302) at weibo4j.Oauth.getAccessTokenByCode(Oauth.java:80) at weibo4j.examples.oauth2.OAuth4Code.main(OAuth4Code.java:22) Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:168) at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293) at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:632) at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:506) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at weibo4j.http.HttpClient.httpRequest(HttpClient.java:396) ... 3 more
调用OAuth4Code 出现WeiboException: Connection reset
0 INFO [2017-07-27 15:38:23] code: 3ea4c7a657c4e1f8e092441e8aafe23f 3 DEBUG [2017-07-27 15:38:23] Request: 3 DEBUG [2017-07-27 15:38:23] POSThttps://api.weibo.com/oauth2/access_token 653 INFO [2017-07-27 15:38:24] I/O exception (java.net.SocketException) caught when processing request: Connection reset 654 INFO [2017-07-27 15:38:24] Retrying request 1042 INFO [2017-07-27 15:38:24] I/O exception (java.net.SocketException) caught when processing request: Connection reset 1043 INFO [2017-07-27 15:38:24] Retrying request 1434 INFO [2017-07-27 15:38:25] I/O exception (java.net.SocketException) caught when processing request: Connection reset 1434 INFO [2017-07-27 15:38:25] Retrying request weibo4j.model.WeiboException: Connection reset at weibo4j.http.HttpClient.httpRequest(HttpClient.java:412) at weibo4j.http.HttpClient.post(HttpClient.java:293) at weibo4j.Oauth.getAccessTokenByCode(Oauth.java:79) at weibo4j.examples.oauth2.OAuth4Code.main(OAuth4Code.java:21) Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:189) at java.net.SocketInputStream.read(SocketInputStream.java:121) at sun.security.ssl.InputRecord.readFully(InputRecord.java:312) at sun.security.ssl.InputRecord.read(InputRecord.java:350) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328) at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:702) at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:122) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:506) at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at weibo4j.http.HttpClient.httpRequest(HttpClient.java:387) ... 3 more
Web项目在weblogic9.2部署,运行报错,单点系统CAS
java.util.concurrent.ExecutionException: java.net.ConnectException: Connection timed out: connect at com.sinosoft.dmsdriver.util.BpsSupport.execute(BpsSupport.java:110) at com.sinosoft.dmsdriver.service.transform.impl.GetUrlByCodeServiceImpl.execute(GetUrlByCodeServiceImpl.java:30) at com.sinosoft.dmsdriver.service.server.DictAPIService.getUrlByCode(DictAPIService.java:218) at cn.com.sinosoft.cas.filter.CustomCASFilter.doFilter(CustomCASFilter.java:180) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:76) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3270) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2019) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1925) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1394) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209) at weblogic.work.ExecuteThread.run(ExecuteThread.java:181) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:367) at java.net.Socket.connect(Socket.java:524) at java.net.Socket.connect(Socket.java:474) at java.net.Socket.<init>(Socket.java:371) at java.net.Socket.<init>(Socket.java:244) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.sinosoft.dmsdriver.util.BpsSupport.execute(BpsSupport.java:84) ... 17 more <2016-11-22 下午02时19分21秒 CST> <Error> <HTTP> <BEA-101017> <[weblogic.servlet.internal.WebAppServletContext@cac02f - appName: 'reins', name: 'webapp', context-path: '/reins'] Root cause of ServletException. javax.servlet.ServletException: When CASFilter protects pages that do not receive a 'ticket' parameter, it needs a edu.yale.its.tp.cas.client.filter.loginUrl filter parameter at cn.com.sinosoft.cas.filter.CustomCASFilter.doFilter(CustomCASFilter.java:328) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:76) at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:42) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) Truncated. see log file for complete stacktrace >
MultipartRequestEntity post 请求发送。接收端用java httpserver httpexchange 接受。能不能单独取出 request sign 两块内容
package com.test.HttpClient; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StreamUtils; /** * Hello world! * */ public class HttpClientApp { private static final Logger logger = LoggerFactory.getLogger(HttpClientApp.class); public static void main( String[] args ) { String url="http://127.0.0.1:8081/SpringMvc1/student"; String reqStr="aaaaaaa"; String contentType="application/json"; String charset="UTF-8"; String ss=doPost( url, reqStr, contentType, charset) ; System.out.println("返回内容为1:" +ss); Part[] parts=new Part[2]; parts[0]=new StringPart("request", "请求报文体",charset); parts[1]=new StringPart("sign", "数字签名",charset); url="http://127.0.0.1:8081/SpringMvc1/BossServlet"; // url="http://127.0.0.1:8081/SpringMvc1/fileupload"; String response=doPostMuStr( url, parts) ; System.out.println("返回内容为1:" +response); } /** * 执行一个HTTP POST请求,返回请求响应的HTML * * @param url 请求的URL地址 * @param reqStr 请求的查询参数,可以为null * @param charset 字符集 * @return 返回请求响应的HTML */ public static String doPost(String url, String reqStr, String contentType, String charset) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); try { HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒) managerParams.setSoTimeout(30000); // 设置读数据超时时间(单位毫秒) method.setRequestEntity(new StringRequestEntity(reqStr, contentType, "utf-8")); client.executeMethod(method); System.out.println("返回的状态码为:" +method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_OK) { // return StreamUtils.copyToString(method.getResponseBodyAsStream(), Charset.forName(charset)); return IOUtils.toString(method.getResponseBodyAsStream(),"utf-8"); } } catch (UnsupportedEncodingException e1) { logger.error(e1.getMessage()); return ""; } catch (IOException e) { logger.error("执行HTTP Post请求" + url + "时,发生异常!" + e.toString()); return ""; } finally { method.releaseConnection(); } return null; } /** * 执行一个HTTP POST请求,返回请求响应的HTML * * @param url 请求的URL地址 * @param reqStr 请求的查询参数,可以为null * @param charset 字符集 * @return 返回请求响应的HTML */ public static String doPostMuStr(String url, Part[] reqStr) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); try { HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams(); managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒) managerParams.setSoTimeout(30000); // 设置读数据超时时间(单位毫秒) method.setRequestEntity(new MultipartRequestEntity(reqStr, method.getParams())); // method.setContentChunked(true); client.executeMethod(method); System.out.println("返回的状态码为:" +method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_OK) { return IOUtils.toString(method.getResponseBodyAsStream(),"utf-8"); } } catch (UnsupportedEncodingException e1) { logger.error(e1.getMessage()); return ""; } catch (IOException e) { logger.error("执行HTTP Post请求" + url + "时,发生异常!" + e.toString()); return ""; } finally { method.releaseConnection(); } return null; } }
servlet中不能使用HttpClient吗?
servlet中不能使用HttpClient吗? 在servlet中使用HttpClient,包已配置好,编译通过。 package use; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import bean.Stock; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import java.util.TimerTask; import java.util.HashMap; import java.util.Timer; public class UseServlet extends HttpServlet { private HashMap<String, Stock> stocks; [b] private HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());[/b] public void init(ServletConfig config) throws ServletException { super.init(config); } ............ ......... 但在网页中调用时,出现错误: [b]javax.servlet.ServletException: Error instantiating servlet class use.UseServlet[/b] org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) java.lang.Thread.run(Unknown Source) 问题在哪?请帮忙看一下!
麻烦大神帮忙看下 java.net.SocketException: Connection reset 不是经常出现间歇性出现
错误代码 java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:210) at java.net.SocketInputStream.read(SocketInputStream.java:141) at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) at java.io.BufferedInputStream.read(BufferedInputStream.java:265) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.example.madame.service.JokeService.jokeGet(JokeService.java:86) at com.example.madame.controller.OneSentencePerDayController.test35(OneSentencePerDayController.java:105) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) 我的代码 public String joke() { try { // String urlTypeName = java.net.URLEncoder.encode(city1, "utf-8"); URL url = new URL("xxx"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { //结果码=200 InputStream is = conn.getInputStream(); //内存流 , ByteArrayOutputStream boas = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while (is.available() != 0&&(len = is.read(buffer)) != -1) { boas.write(buffer, 0, len); } System.out.println("GET请求获取的数据:" + boas.toString()); JSONObject jsonObject = JSONObject.fromObject(boas.toString()); String reason = String.valueOf(jsonObject.get("reason")); if ("success".equals(reason)) { Object result = jsonObject.get("result"); JSONArray jsonArray = JSONArray.fromObject(result.toString()); int count = 0; String joke = ""; if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { String content = String.valueOf(JSONObject.fromObject(jsonArray.get(i)).get("content")); count += 1; joke += " <tr align=\"center\" style=\"text-indent:2em;\">\n" + " <td >" + count + "." + content + "</td>\n" + " </tr>"; if (count == 3) { break; } } boas.close(); is.close(); return joke; } } } } catch (IOException e) { e.printStackTrace(); } return null; }
jsp xml形式的酒店接口查询!!
最近,项目中开发中,遇到需要查询酒店信息这个功能模块!!酒店信息是一个专门的服务商提供的,查询以及接收酒店信息都是以XML形式!!现在,我项目是jsp+Struts+Hibernate 开发的!!我不知道jsp form表单数据如何转换成提供商的那种xml形式继而发送请求!! 发送请求xml: <OTRequest> <TransactionName>HotelSearch</TransactionName> <Header> <SessionID>1111111111</SessionID> <!--假设登陆指令返回的sessionID为1111111111--> <Invoker>HBE</Invoker> </Header> <IdentityInfo> <OfficeID>请输入申请ID</OfficeID> <UserID></UserID> <Password>请输入密码</Password> </IdentityInfo> <ScrollingInfo> <DisplayReq>30</DisplayReq> <PageItems>10</PageItems> <PageNo>1</PageNo> </ScrollingInfo> <SearchConditions> <GDS></GDS> <CheckInDate>20070901</CheckInDate> <CheckOutDate>20070903</CheckOutDate> <PropertyDetail> <CityCode>PEK</CityCode> <Supplier></Supplier> <PropertyName/> <Transportation/> <PorName/> <CityRegion/> <AreaCode/> <RankCode/> </PropertyDetail> <RateDetail> <PaymentType/> <Currency></Currency> <RateMin></RateMin> <RateMax></RateMax> <RateCode/> </RateDetail> <RoomDetail></RoomDetail> </SearchConditions> </OTRequest> 接收xml: <?xml version="1.0" encoding="GB2312" ?> - <OTResponse> <TransactionName>Any</TransactionName> - <ErrorInfo> <Code>-1</Code> <Description>....</Description> </ErrorInfo> <Data /> </OTResponse> java类: import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; ………… try { req = new String(req.getBytes("GB2312"), "ISO8859_1"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); }//纠正输入乱码问题,本例中开发环境使用了GB2312编码 org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); String strUrl = " http://202.103.129.25/HBE/servlet/tdplogicbookingcontroller"; org.apache.commons.httpclient.methods.PostMethod method = new org.apache.commons.httpclient.methods.PostMethod(strUrl); method.setParameter("request", req); org.apache.commons.httpclient.DefaultMethodRetryHandler retryhandler = new org.apache.commons.httpclient.DefaultMethodRetryHandler(); retryhandler.setRequestSentRetryEnabled(false); retryhandler.setRetryCount(3); method.setMethodRetryHandler(retryhandler); client.executeMethod(method); InputStream is = method.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is,"GB2312")); StringBuffer s = new StringBuffer(); String tmp; while((tmp=reader.readLine())!=null) { s.append(tmp); } req为以XML形式拼装的请求字符串 不知道jsp里form表单数据如何拼装成xml 存在request里!! 谢谢!!谢谢!!!!
<自己动手写网络爬虫>时遇到的报错
package com.guet.crawlerbyself; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; public class RetrivePage { private static HttpClient httpClient = new HttpClient(); //set a proxy server static { //set IP Address and the port of the proxy server httpClient.getHostConfiguration().setProxy("localhost",8080); } public static boolean downloadPage(String path) throws HttpException, IOException { InputStream input = null; OutputStream output = null; //get post method PostMethod postMethod = new PostMethod("www.baidu.com"); //set parameters of post method NameValuePair[] postData = new NameValuePair[2]; postData[0] = new NameValuePair("name","baidu"); postData[1] = new NameValuePair("password","123"); //Adds an array of parameters to be used in the POST request body. postMethod.addParameters(postData); //execute and return status code. int statusCode = httpClient.executeMethod(postMethod); //this place,only process the status 200. if(statusCode == HttpStatus.SC_OK) { input = postMethod.getResponseBodyAsStream(); String filename = path.substring(path.lastIndexOf('/')+1); output = new FileOutputStream(filename); //output to the file int tempByte = -1; while((tempByte = input.read())>0){ output.write(tempByte); } if (input != null ){ input.close(); } if(output != null){ output.close(); } return true; } return false; } public static void main(String[] args) { System.out.println("execute"); try{ RetrivePage.downloadPage("http://www.baidu.com/"); }catch(HttpException e){ System.out.println("httpexeption"); e.printStackTrace(); }catch(IOException e){ System.out.println("ioexeption"); e.printStackTrace(); } } } 运行时弹出对话框显示:could not find the main class. program will exit console中显示: java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.commons.httpclient.HttpClient.<clinit>(HttpClient.java:66) at com.guet.crawlerbyself.RetrivePage.<clinit>(RetrivePage.java:17) Exception in thread "main" 所需的apache的开源包我已经导入了,代码写完后也没报错,运行的时候就报错了. 我在网上google了一下,有的说把jdk改成1.4的之类的答案,我试过了,还是老问题没什么效果.希望之前碰到这个问题的朋友帮忙解答一下.
测试报错,Connection refused: connect,求解?
代码: ``` public class ItfTest { /** * @param args */ public static void main(String[] args) { try { String out = testbiz(); System.out.println(out); } catch (IOException e) { e.printStackTrace(); } } public static String testbiz() throws HttpException, IOException { HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod( "http://localhost:8001/itf/OI_AddSaleByParameter"); // PostMethod post = new PostMethod( "https://rryx.sinovatech.com/itf/OI_QueryEShopOrder"); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); String key = "123321abc"; String channel="ch_shenxun"; Map<String, Object> req = new HashMap<>(); String instr ="{\"body\": \"{\\\"startTime\\\":\\\"2019-01-01 14:43:19\\\",\\\"endTime\\\":\\\"2019-01-12 15:14:42\\\",\\\"phone\\\":\\\"18309858042\\\"}\",\"head\": {} }"; /* String instr ="6351"; req.put("loginCode",instr);*/ Map<String, Object> header = new HashMap<>(); header.put("appId", channel); header.put("tid", UUID.randomUUID().toString()); header.put("timestamp", System.currentTimeMillis()); header.put("ver", "1.0"); Map<String, Object> reMap = new HashMap<>(); reMap.put("header", header); reMap.put("req", req); req.put("saleName","123"); req.put("goodIds","ff8080815e562c4d015e6103956700b6"); req.put("orderValue","1"); req.put("createName","管理员"); System.out.println(JSONObject.toJSON(reMap)); String reqdata = JSONObject.toJSONString(reMap); String sign = DigestUtils.md5Hex(reqdata + key); NameValuePair[] param = { new NameValuePair("sign", sign), new NameValuePair("reqdata", reqdata) }; post.setRequestBody(param); int result = httpClient.executeMethod(post); System.out.println("返回结果=" + result); InputStream in = post.getResponseBodyAsStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } reader.close(); return sb.toString(); } } //以上代码传参测试,但是运行后报错 java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at java.net.Socket.<init>(Socket.java:434) at java.net.Socket.<init>(Socket.java:286) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) at com.sinovatech.test.ItfTest.testbiz(ItfTest.java:95) at com.sinovatech.test.ItfTest.main(ItfTest.java:52) 求大神指点 ```
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了无数
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
大学四年自学走来,这些珍藏的「实用工具/学习网站」我全贡献出来了
知乎高赞:文中列举了互联网一线大厂程序员都在用的工具集合,涉及面非常广,小白和老手都可以进来看看,或许有新收获。
《阿里巴巴开发手册》读书笔记-编程规约
Java编程规约命名风格 命名风格 类名使用UpperCamelCase风格 方法名,参数名,成员变量,局部变量都统一使用lowerCamelcase风格 常量命名全部大写,单词间用下划线隔开, 力求语义表达完整清楚,不要嫌名字长 ...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
你知道的越多,你不知道的越多 点赞再看,养成习惯 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试点思维导图,也整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。 前前言 为啥今天有个前前言呢? 因为你们的丙丙啊,昨天有牌面了哟,直接被微信官方推荐,知乎推荐,也就仅仅是还行吧(心里乐开花)
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
Python爬虫精简步骤1 获取数据
爬虫的工作分为四步: 1.获取数据。爬虫程序会根据我们提供的网址,向服务器发起请求,然后返回数据。 2.解析数据。爬虫程序会把服务器返回的数据解析成我们能读懂的格式。 3.提取数据。爬虫程序再从中提取出我们需要的数据。 4.储存数据。爬虫程序把这些有用的数据保存起来,便于你日后的使用和分析。 这一篇的内容就是:获取数据。 首先,我们将会利用一个强大的库——requests来获取数据。 在电脑上安装
Python绘图,圣诞树,花,爱心 | Turtle篇
1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle() circle.shape('circle') circle.color('red') circle.speed('fastest') circle.up() square = turtle.Turtle()
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 更多有趣分析教程,扫描下方二维码关注vx公号「裸睡的猪」 即可查看! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
别低估自己的直觉,也别高估自己的智商
所有群全部吵翻天,朋友圈全部沦陷,公众号疯狂转发。这两周没怎么发原创,只发新闻,可能有人注意到了。我不是懒,是文章写了却没发,因为大家的关注力始终在这次的疫情上面,发了也没人看。当然,我...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。   再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。   下文是原回答,希望能对你能有所启发。   如果我说,这个世界上人真的分三六九等,
为什么听过很多道理,依然过不好这一生?
记录学习笔记是一个重要的习惯,不希望学习过的东西成为过眼云烟。做总结的同时也是一次复盘思考的过程。 本文是根据阅读得到 App上《万维钢·精英日课》部分文章后所做的一点笔记和思考。学习是一个系统的过程,思维模型的建立需要相对完整的学习和思考过程。以下观点是在碎片化阅读后总结的一点心得总结。
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计
Linux 命令(122)—— watch 命令
1.命令简介 2.命令格式 3.选项说明 4.常用示例 参考文献 [1] watch(1) manual
Linux 命令(121)—— cal 命令
1.命令简介 2.命令格式 3.选项说明 4.常用示例 参考文献 [1] cal(1) manual
记jsp+servlet+jdbc实现的新闻管理系统
1.工具:eclipse+SQLyog 2.介绍:实现的内容就是显示新闻的基本信息,然后一个增删改查的操作。 3.数据库表设计 列名 中文名称 数据类型 长度 非空 newsId 文章ID int 11 √ newsTitle 文章标题 varchar 20 √ newsContent 文章内容 text newsStatus 是否审核 varchar 10 news...
Python新型冠状病毒疫情数据自动爬取+统计+发送报告+数据屏幕(三)发送篇
今天介绍的项目是使用 Itchat 发送统计报告 项目功能设计: 定时爬取疫情数据存入Mysql 进行数据分析制作疫情报告 使用itchat给亲人朋友发送分析报告(本文) 基于Django做数据屏幕 使用Tableau做数据分析 来看看最终效果 目前已经完成,预计2月12日前更新 使用 itchat 发送数据统计报告 itchat 是一个基于 web微信的一个框架,但微信官方并不允
相关热词 c# 识别回车 c#生成条形码ean13 c#子控制器调用父控制器 c# 写大文件 c# 浏览pdf c#获取桌面图标的句柄 c# list反射 c# 句柄 进程 c# 倒计时 线程 c# 窗体背景色
立即提问