一、介绍
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.0.3。
二、项目背景
一个省级平台,由很多家单位共同开发然后集成。
资源:各家单位在相互集成过程中,会调用提供webservice接口。同时还有不是WS接口部分。
本项目中用到的第三方组件是apache的httpclient,一个非常强大的网页抓取工具(抓这个字用得可能不太好),
示例:
public static void main(String args[]){ HttpHost target = new HttpHost("126.33.8.123",7001,"http"); // general setup SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // prepare parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); //的网站会先判别用户的请求是否是来自浏览器,如不是,则返回不正确的文本 HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.2)"); ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params); try { HttpGet req = new HttpGet("/sgs_portal/login.action?loginname=admin&loginpwd=123456"); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); if (entity != null) { System.out.println(">>>: "+EntityUtils.toString(entity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //关闭连接 httpclient.getConnectionManager().shutdown(); } }
上面方法中 只要 action 有输出即可,可为xml 、json等