除了HttpClient,Java九色腾类似的还有什么么类似HttpClient的技术

除了HttpClient,Java还有什么类似HttpClient的技术呢? - ITeye问答
除了HttpClient,Java还有什么类似HttpClient的技术呢?求大神指导!
给你个例子:
import java.io.IOE
import java.net.MalformedURLE
import com.gargoylesoftware.htmlunit.BrowserV
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeE
import com.gargoylesoftware.htmlunit.WebC
import com.gargoylesoftware.htmlunit.html.HtmlA
import com.gargoylesoftware.htmlunit.html.HtmlE
import com.gargoylesoftware.htmlunit.html.HtmlP
* 使用HtmlUnit模拟浏览器的操作
* HtmlUnit 2.7及以前版本基于HttpClient 3.x,
* HtmlUnit 2.8及以后版本基于HttpClient 4.x,
* 而HttpClient 3.x和HttpClient 4.x差别很大,所以HtmlUnit 2.7跟以后的版本差别也很大
* @author 陈峰
public class HtmlUnitDemo1 {
* 模拟登录,登录成功后点击链接显示另一个页面
* @param args
* @throws IOException
* @throws MalformedURLException
* @throws FailingHttpStatusCodeException
public static void main(String[] args)
throws FailingHttpStatusCodeException, MalformedURLException,
IOException {
// 创建浏览器,可以选择IE、FF等等
WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_7);
// 获取某网站页面
HtmlPage loginPage = client
.getPage("http://localhost:8080/cfStruts2Ex2/login.action");
// 获取某页面元素,可通过id或name,(具体方式很多 --Foxswily)
HtmlElement usernameElmt = loginPage
.getElementById("LoginAction_username");
// HtmlElement elmt = page.getElementByName("somename");
// 此例以文本框为例,先点击,再输入,完全跟实际浏览器行为一致
usernameElmt.click();
usernameElmt.type("root");
HtmlElement passwordElmt = loginPage
.getElementById("LoginAction_password");
passwordElmt.click();
passwordElmt.type("chenfeng");
// 获取按钮
HtmlElement loginBtn = loginPage.getElementById("LoginAction_login");
// HtmlSubmitInput loginBtn = (HtmlSubmitInput) loginPage
// .getElementById("LoginAction_login");
// HtmlButton loginBtn = (HtmlButton)
// page.getElementById("LoginAction_login");
// 点击并获得返回结果
HtmlPage loginResultPage = loginBtn.click();
// 结果拿到了,想干啥您随意
String loginResultContent = loginResultPage.getWebResponse()
.getContentAsString();
System.out.println(loginResultContent);
// 如果登录成功
if (null != loginResultContent
&& loginResultContent.indexOf("Welcome,") & 0) {
// 获得HTML链接并点击该链接
HtmlAnchor showbookBtn = (HtmlAnchor) loginResultPage
.getElementById("showbook");
HtmlPage showBookPage = showbookBtn.click();
System.out
.println("\n\n===========================================================");
System.out.println(showBookPage.getWebResponse()
.getContentAsString());
更直接一点吧,用jdk自带的urlconnection来实现,无需依赖其他库。下边的示例实现了post和get方法。
示例如下:
public class HttpUtil {
public static final String CHARSET = "UTF-8";
public static String post(String url, Map&String, String& postParams) {
HttpURLConnection con =
OutputStream osw =
InputStream ins =
con = (HttpURLConnection) new URL(url).openConnection();
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
if (null != postParams) {
con.setDoOutput(true);
String postParam = encodeParameters(postParams);
byte[] bytes = postParam.getBytes(CHARSET);
con.setRequestProperty("Content-Length",
Integer.toString(bytes.length));
osw = con.getOutputStream();
osw.write(bytes);
osw.flush();
int resCode = con.getResponseCode();
if (resCode & 400) {
ins = con.getInputStream();
ins = con.getErrorStream();
return readContent(ins);
} catch (IOException e) {
} finally {
if (osw != null) {
osw.close();
if (ins != null) {
ins.close();
} catch (IOException e) {
e.printStackTrace();
public static String get(String url) {
HttpURLConnection con =
OutputStream osw =
InputStream ins =
con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("GET");
int resCode = con.getResponseCode();
if (resCode & 400) {
ins = con.getInputStream();
ins = con.getErrorStream();
return readContent(ins);
} catch (IOException e) {
} finally {
if (osw != null) {
osw.close();
if (ins != null) {
ins.close();
} catch (IOException e) {
e.printStackTrace();
private static final String readContent(InputStream ins) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(ins,
HttpUtil.CHARSET));
if (ins != null) {
while ((line = br.readLine()) != null) {
sb.append(line);
return sb.toString();
public static String encodeParameters(Map&String, String& postParams) {
StringBuilder buf = new StringBuilder();
if (postParams != null && postParams.size() & 0) {
for (Map.Entry&String, String& tmp : postParams.entrySet()) {
buf.append(URLEncoder.encode(tmp.getKey(), CHARSET))
.append("=")
.append(URLEncoder.encode(tmp.getValue(), CHARSET))
.append("&");
} catch (java.io.UnsupportedEncodingException neverHappen) {
buf.deleteCharAt(buf.length() - 1);
return buf.toString();
有java原生的HttpUrlConnection呢,如果要是单元测试的话,还有EasyMock和Jmock。
httpClient还有一个异步的HttpAsyntClient
HtmlUnit,可以模拟浏览器的操作。
本来是用于自动化测试的,但是开发中也能实现强大的功能。
用于模拟登录,有时候比HttpClient更好用。
不过,HtmlUnit是基于HttpClient的。
已解决问题
未解决问题爬虫,有什么框架比httpclient更快?可以支持post请求的和代理的 - 知乎3被浏览1259分享邀请回答0添加评论分享收藏感谢收起64879人阅读
Web/数据/云计算(68)
httpclient是apache的一个项目:
文档比较完善:
这里就不啰嗦了,主要是在做demo的时候遇到的一些问题在这里总结一下:
[引用请注明出处]
1、使用连接池
虽说http协议时无连接的,但毕竟是基于tcp的,底层还是需要和服务器建立连接的。对于需要从同一个站点抓取大量网页的程序,应该使用连接池,否则每次抓取都和Web站点建立连接、发送请求、获得响应、释放连接,一方面效率不高,另一方面稍不小心就会疏忽了某些资源的释放、导致站点拒绝连接(很多站点会拒绝同一个ip的大量连接、防止DOS攻击)。
连接池的例程如下:
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme(&http&, 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme(&https&, 443, SSLSocketFactory.getSocketFactory()));
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(2);
HttpHost googleResearch = new HttpHost(&&, 80);
HttpHost wikipediaEn = new HttpHost(&en.wikipedia.org&, 80);
cm.setMaxPerRoute(new HttpRoute(googleResearch), 30);
cm.setMaxPerRoute(new HttpRoute(wikipediaEn), 50);
SchemaRegistry的作用是注册协议的默认端口号。PoolingClientConnectionManager是池化连接管理器,即连接池,setMaxTotal设置连接池的最大连接数,setDefaultMaxPerRoute设置每个路由()上的默认连接个数,setMaxPerRoute则单独为某个站点设置最大连接个数。
从连接池中获取http client也很方面:
DefaultHttpClient client = new DefaultHttpClient(cm);
2、设置HttpClient参数
HttpClient需要设置合适的参数,才能更好地工作。默认的参数能够应付少量的抓取工作,但找到一组合适的参数往往能改善特定情况下的抓取效果。设置参数的例程如下:
DefaultHttpClient client = new DefaultHttpClient(cm);
Integer socketTimeout = 10000;
Integer connectionTimeout = 10000;
final int retryTime = 3;
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
client.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, false);
client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024 * 1024);
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler()
public boolean retryRequest(IOException exception, int executionCount, HttpContext context)
if (executionCount &= retryTime)
// Do not retry if over max retry count
if (exception instanceof InterruptedIOException)
// Timeout
if (exception instanceof UnknownHostException)
// Unknown host
if (exception instanceof ConnectException)
// Connection refused
if (exception instanceof SSLException)
// SSL handshake exception
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent)
// Retry if the request is considered idempotent
client.setHttpRequestRetryHandler(myRetryHandler);
5、6行分别设置了Socket最大等待时间、连接最大等待时间(单位都是毫秒)。socket等待时间是指从站点下载页面和数据时,两个数据包之间的最大时间间隔,超过这个时间间隔,httpclient就认为连接出了故障。连接最大等待时间则是指和站点建立连接时的最大等待时间,超过这个时间站点不给回应,则认为站点无法连接。第7行设置httpclient不使用NoDelay策略。如果启用了NoDelay策略,httpclient和站点之间传输数据时将会尽可能及时地将发送缓冲区中的数据发送出去、而不考虑网络带宽的利用率,这个策略适合对实时性要求高的场景。而禁用了这个策略之后,数据传输会采用Nagle's
algorithm发送数据,该算法会充分顾及带宽的利用率,而不是数据传输的实时性。第8行设置socket缓冲区的大小(单位为字节),默认是8KB。
HttpRequestRetryHandler是负责处理请求重试的接口。在该接口的内部类中实现RetryRequest方法即可。当httpclient发送请求之后出现异常时,就会调用这个方法。在该方法中根据已执行请求的次数、请求内容、异常信息判断是否继续重试,若继续重试返回true,否则返回false。
3、设置request header
设置request header也是很重要的,比如设置User-Agent可以将抓取程序伪装成浏览器,骗过一些网站对爬虫的检查,设置Accept-Encoding为gzip可以建议站点以压缩格式传输数据、节省带宽等等。例程如下:
HttpResponse response =
HttpGet get = new HttpGet(url);
get.addHeader(&Accept&, &text/html&);
get.addHeader(&Accept-Charset&, &utf-8&);
get.addHeader(&Accept-Encoding&, &gzip&);
get.addHeader(&Accept-Language&, &en-US,en&);
get.addHeader(&User-Agent&, &Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0. Safari/537.22&);
response = client.execute(get);
HttpEntity entity = response.getEntity();
Header header = entity.getContentEncoding();
if (header != null)
HeaderElement[] codecs = header.getElements();
for (int i = 0; i & codecs. i++)
if (codecs[i].getName().equalsIgnoreCase(&gzip&))
response.setEntity(new GzipDecompressingEntity(entity));
各个header的含义参考
需要的都设上就好了。如果需要很多不同的User-Agent轮流使用(同一个User-Agent对一个站点频繁访问容易被识别为爬虫而杯具),可以去网上找,也可以在自己的chrome浏览器里看或者用抓包软件抓。值得注意的是设置了Accept-Encoding为gzip之后,对站点回复的内容要检查是否是压缩格式的,如果是,则解压缩,如上面例程中第9行之后的代码所示。
[引用请注明出处]
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:765603次
积分:6889
积分:6889
排名:第3302名
原创:132篇
评论:143条
(4)(1)(4)(1)(3)(1)(1)(1)(1)(4)(3)(10)(5)(6)(11)(7)(6)(2)(1)(4)(2)(4)(5)(15)(3)(8)(12)(7)(6)(1)(3)Java与Http协议(HttpURLConnection和HttpClient)
引言&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&& http(超文本传输协议)是一个基于请求与响应模式的、无状态的、应用层的协议,常基于TCP的连接方式。HTTP协议的主要特点是:
&&&& 1.支持客户/服务器模式。
&&&& 2.简单快速:客户向服务器请求服务时,只需传送请求方法和路径。由于HTTP协议简单,通信速度很快。
&&&& 3.灵活:HTTP允许传输任意类型的数据对象。类型由Content-Type加以标记。
&&&& 4.无连接:即每次连接只处理一个请求,处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间。
&&&& 5.无状态:无状态是指协议对于事务处理没有记忆能力。
&&&& http1.0协议默认的是非持久连接, HTTP1.1默认的连接方式为持久连接。
非持久连接:每次服务器发出一个对象后,相应的TCP连接就被关闭,也就是说每个连接都没有持续到可用于传送其他对象。每个TCP连接只用于传输一个请求消息和一个响应消息。
持久连接:服务器在发出响应后让TCP连接继续打开着。同一对客户/服务器之间的后续请求和响应可以通过这个连接发送。HTTP/1.1的默认模式使用带流水线的持久连接。
一、HTTP协议详解之请求
[java] view plaincopyprint?//请求行&&
POST /reg. HTTP/ (CRLF)&&&&&&&&
//消息报头&&
Accept:image/gif,image/x-xbitmap,image/jpeg,application/x-shockwave-flash,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/* (CRLF)&
Accept-Language:zh-cn (CRLF)&
Accept-Encoding:gzip,deflate (CRLF)&
If-Modified-Since:Wed,05 Jan :25 GMT (CRLF)&
If-None-Match:W/&80b1a4c018f3c41:8317& (CRLF)&
User-Agent:Mozilla/4.0(MSIE6.0;Windows NT 5.0) (CRLF)&
Host:www. (CRLF)&
Connection:Keep-Alive (CRLF)&
//请求正文&&
user=jeffrey&pwd=1234&
POST /reg.jsp HTTP/ (CRLF)&&&&&&
//消息报头
Accept:image/gif,image/x-xbitmap,image/jpeg,application/x-shockwave-flash,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/* (CRLF)
Accept-Language:zh-cn (CRLF)
Accept-Encoding:gzip,deflate (CRLF)
If-Modified-Since:Wed,05 Jan :25 GMT (CRLF)
If-None-Match:W/&80b1a4c018f3c41:8317& (CRLF)
User-Agent:Mozilla/4.0(MSIE6.0;Windows NT 5.0) (CRLF)
Host:www. (CRLF)
Connection:Keep-Alive (CRLF)
//请求正文
user=jeffrey&pwd=1234
以上是http请求的三部:请求行、消息报头、请求正文。
&&&& 请求行以一个方法符号开头,以空格分开,后面跟着请求的URI和协议的版本,格式如下:
Method Request-URI HTTP-Version CRLF&
&&&& 其中 Method表示请求方法(如POST、GET、PUT、DELETE等);Request-URI是一个统一资源标识符;HTTP-Version表示请求的HTTP协议版本;CRLF表示回车和换行。
二、HTTP协议详解之响应篇
[java]& //状态行&&
HTTP/1.1 200 OK (CRLF)&
//消息报头&&
Cache-Control: private, max-age=30&
Content-Type: text/ charset=utf-8&
Content-Encoding: gzip&
Expires: Mon, 25 May :33 GMT&
Last-Modified: Mon, 25 May :03 GMT&
Vary: Accept-Encoding&
Server: Microsoft-IIS/7.0&
X-AspNet-Version: 2.0.50727&
X-Powered-By: ASP.NET&
Date: Mon, 25 May :02 GMT&
Content-Length: 12173&
//响应正文&&
HTTP/1.1 200 OK (CRLF)
//消息报头
Cache-Control: private, max-age=30
Content-Type: text/ charset=utf-8
Content-Encoding: gzip
Expires: Mon, 25 May :33 GMT
Last-Modified: Mon, 25 May :03 GMT
Vary: Accept-Encoding
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Mon, 25 May :02 GMT
Content-Length: 12173
//响应正文
HTTP响应也是由三个部分组成,分别是:状态行、消息报头、响应正文
&&&& 状态行格式如下:
&&&&&&&&& HTTP-Version Status-Code Reason-Phrase CRLF
&&&& 其中,HTTP-Version表示服务器HTTP协议的版本;Status-Code表示服务器发回的响应状态代码;Reason-Phrase表示状态代码的文本描述。
常见状态代码、状态描述、说明:
200 OK&&&&& //客户端请求成功
400 Bad Request& //客户端请求有语法错误,不能被服务器所理解
401 Unauthorized //请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用
403 Forbidden& //服务器收到请求,但是拒绝提供服务
404 Not Found& //请求资源不存在,eg:输入了错误的URL
500 Internal Server Error //服务器发生不可预期的错误
503 Server Unavailable& //服务器当前不能处理客户端的请求,一段时间后可能恢复正常
三、HTTP协议详解之消息报头
&&&&&&& HTTP消息由客户端到服务器的请求和服务器到客户端的响应组成。请求消息和响应消息都是由开始行(对于请求消息,开始行就是请求行;对于响应消息,开始行就是状态行),消息报头(可选),空行(只有CRLF的行),消息正文(可选)组成。
&&&&&&& HTTP消息报头包括普通报头、请求报头、响应报头、实体报头。每一个报头域都是由名字+&:&+空格+值 组成,消息报头域的名字是大小写无关的。
1、请求报头
&&&& 请求报头允许客户端向服务器端传递请求的附加信息以及客户端自身的信息。
常用的请求报头
Accept请求报头域用于指定客户端接受哪些类型的信息。
Accept-Charset请求报头域用于指定客户端接受的字符集。
Accept-Encoding请求报头域类似于Accept,但是它是用于指定可接受的内容编码。
Accept-Language请求报头域类似于Accept,但是它是用于指定一种自然语言。
Authorization请求报头域主要用于证明客户端有权查看某个资源。
Host请求报头域主要用于指定被请求资源的Internet主机和端口号,它通常从HTTP URL中提取出来的。User-Agent请求报头域允许客户端将它的操作、和其它属性告诉服务器。
2、响应报头
&&&& 响应报头允许服务器传递不能放在状态行中的附加响应信息,以及关于服务器的信息和对Request-URI所标识的资源进行下一步访问的信息。
常用的响应报头
Location响应报头域用于重定向接受者到一个新的位置。Location响应报头域常用在更换域名的时候。
Server响应报头域包含了服务器用来处理请求的软件信息
3. 实体报头
请求和响应消息都可以传送一个实体。
常用的实体报头
Content-Encoding指示已经被应用到实体正文的附加内容的编码。
Content-Language实体报头域描述了资源所用的自然语言。
Content-Length实体报头域用于指明实体正文的长度,以字节方式存储的十进制数字来表示。
Content-Type实体报头域用语指明发送给接收者的实体正文的媒体类型。
Last-Modified实体报头域用于指示资源的最后修改日期和时间。
Expires实体报头域给出响应过期的日期和时间。
1、HTTP协议Content Lenth限制导致拒绝服务攻击
使用POST方法时,可以设置ContentLenth来定义需要传送的数据长度,例如ContentLenth:,在传送完成前,内 存不会释放,攻击者可以利用这个缺陷,连续向WEB服务器发送垃圾数据直至WEB服务器内存耗尽。这种攻击方法基本不会留下痕迹。
2、为了提高用户使用浏览器时的性能,现代浏览器还支持并发的访问方式,浏览一个网页时同时建立多个连接,以迅速获得一个网页上的多个图标,这样能更快速完成整个网页的传输。HTTP1.1中提供了这种持续连接的方式,而下一代HTTP协议:HTTP-NG更增加了有关会话控制、丰富的内容协商等方式的支持,来提供更高效率的连接。
五.利用HTTP协议实现联网和下载
Url的请求连接(Get方式)
[java]& String currentUrl=&/login.jsp?userName='Devin'&passWord='mypassword'&; //URL ?后面的内容为HTTP请求的正文URL url = new URL(currentUrl);&&
HttpURLConnection httpurlconnection = url.openConnection();//下面的设置对应HTTP请求中的消息报头&&
httpurlconnection.setRequestProperty(&User-Agent&,CommonValues.User_Agent);&
httpurlconnection.setRequestProperty(&Accept&,CommonValues.Accept);&
httpurlconnection.setRequestProperty(&Accept-Charset&,CommonValues.Accept_Charset);&
httpurlconnection.setRequestProperty(&Accept-Language&,CommonValues.Accept_Language);&
httpurlconnection.setRequestProperty(&Connection&,CommonValues.Connection);&
httpurlconnection.setRequestProperty(&Keep-Alive&,CommonValues.Keep_Alive);&
httpurlconnection.setConnectTimeout(CommonValues.ConnectionTimeOut);&
httpurlconnection.setReadTimeout(CommonValues.ReadTimeOut);&
&&&&&&&&&&&&&&
httpurlconnection.connect();&
&&&&&&&&&&&&&
int responsecode = httpurlconnection.getResponseCode();&
&&&&&&&&&&&&&&
if(responsecode == HttpURLConnection.HTTP_OK) //对应HTTP响应中状态行的响应码{&&
  //操作请求流,这里对应HTTP响应中的响应正文&&
&&&&&&&&&&&&&&
if (httpurlconnection != null)&&
&& httpurlconnection.disconnect();&
String currentUrl=&/login.jsp?userName='Devin'&passWord='mypassword'&; //URL ?后面的内容为HTTP请求的正文URL url = new URL(currentUrl);
HttpURLConnection httpurlconnection = url.openConnection();//下面的设置对应HTTP请求中的消息报头
httpurlconnection.setRequestProperty(&User-Agent&,CommonValues.User_Agent);
httpurlconnection.setRequestProperty(&Accept&,CommonValues.Accept);
httpurlconnection.setRequestProperty(&Accept-Charset&,CommonValues.Accept_Charset);
httpurlconnection.setRequestProperty(&Accept-Language&,CommonValues.Accept_Language);
httpurlconnection.setRequestProperty(&Connection&,CommonValues.Connection);
httpurlconnection.setRequestProperty(&Keep-Alive&,CommonValues.Keep_Alive);
httpurlconnection.setConnectTimeout(CommonValues.ConnectionTimeOut);
httpurlconnection.setReadTimeout(CommonValues.ReadTimeOut);
&&&&&&&&&&&&
httpurlconnection.connect();
&&&&&&&&&&&
int responsecode = httpurlconnection.getResponseCode();
&&&&&&&&&&&&
if(responsecode == HttpURLConnection.HTTP_OK) //对应HTTP响应中状态行的响应码{
  //操作请求流,这里对应HTTP响应中的响应正文
&&&&&&&&&&&&
if (httpurlconnection != null)
&& httpurlconnection.disconnect();
六、HttpURLConnection和HttpClient
1.概念&&&&&
&&&&& HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
&&&&& 除此之外,在中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。
HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
& URLConnection
&HTTPClient
Proxies and SOCKS
&Full support in Netscape browser, appletviewer, and applications (SOCKS: Version 4 only); no additional limitations from security policies.
&Full support (SOCKS: Version 4 and 5); limited in applets however
in Netscape can't pick up the settings from the browser.
Authorization
&Full support for Basic Authorization in Netscape (can use info given by the user for normal accesses outside of the applet); no support in appletviewer or applications.
&Ful however cannot access previously given info from Netscape, thereby possibly requesting the user to enter info (s)he has already given for a previous access. Also, you can add/implement additional authentication mechanisms yourself.
&Only has GET and POST.
&Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.
&Currently you can only set any request headers if you are doing a POST under N for GETs and the JDK you can't set any headers.
Under Netscape 3.0 you can read headers only if the resource was returned with a Content- if no Content-length header was returned, or under previous versions of Netscape, or using the JDK no headers can be read.
&Allows any arbitrary headers to be sent and received.
Automatic Redirection Handling
&Yes (as allowed by the HTTP/1.1 spec).
Persistent Connections
&No support currently in JDK; under Netscape uses HTTP/1.0 Keep-Alive's.
&Supports HTTP/1.0 Keep-Alive's and HTTP/1.1 persistence.
Pipelining of Requests
Can handle protocols other than HTTP
&T however only http is currently implemented.
Can do HTTP over SSL (https)
&Under Netscape, yes. Using Appletviewer or in an application, no.
&No (not yet).
Source code available
URLConnection
[java] String urlAddress = &http://192.168.1.102:8080/AndroidServer/login.do&;&&&
&&& URL&&&
&&& HttpURLConnection uRLC&&&
&&& public UrlConnectionToServer(){&&&
&&& }&&&&& //向服务器发送get请求&&
&&& public String doGet(String username,String password){&&&
&&&&&&& String getUrl = urlAddress + &?username=&+username+&&password=&+&&&
&&&&&&& try {&&&
&&&&&&&&&&& url = new URL(getUrl);&&&
&&&&&&&&&&& uRLConnection = (HttpURLConnection)url.openConnection();&&&
&&&&&&&&&&& InputStream is = uRLConnection.getInputStream();&&&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&&&
&&&&&&&&&&& String response = &&;&&&
&&&&&&&&&&& String readLine =&&&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&&&
&&&&&&&&&&&&&&& //response = br.readLine();&&&&
&&&&&&&&&&&&&&& response = response + readL&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& is.close();&&&
&&&&&&&&&&& br.close();&&&
&&&&&&&&&&& uRLConnection.disconnect();&&&
&&&&&&&&&&&&&&
&&&&&&& } catch (MalformedURLException e) {&&&
&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&&&&&&&&&
&&&&&&& } catch (IOException e) {&&&
&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&&&&&&&&&
&&&&&&& }&&&
&&&&&&&&& //向服务器发送post请求&&
&&& public String doPost(String username,String password){&&&
&&&&&&& try {&&&
&&&&&&&&&&& url = new URL(urlAddress);&&&
&&&&&&&&&&& uRLConnection = (HttpURLConnection)url.openConnection();&&&
&&&&&&&&&&& uRLConnection.setDoInput(true);&&&
&&&&&&&&&&& uRLConnection.setDoOutput(true);&&&
&&&&&&&&&&& uRLConnection.setRequestMethod(&POST&);&&&
&&&&&&&&&&& uRLConnection.setUseCaches(false);&&&
&&&&&&&&&&& uRLConnection.setInstanceFollowRedirects(false);&&&
&&&&&&&&&&& uRLConnection.setRequestProperty(&Content-Type&, &application/x-www-form-urlencoded&);&&&
&&&&&&&&&&& uRLConnection.connect();&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());&&&
&&&&&&&&&&& String content = &username=&+username+&&password=&+&&&
&&&&&&&&&&& out.writeBytes(content);&&&
&&&&&&&&&&& out.flush();&&&
&&&&&&&&&&& out.close();&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& InputStream is = uRLConnection.getInputStream();&&&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&&&
&&&&&&&&&&& String response = &&;&&&
&&&&&&&&&&& String readLine =&&&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&&&
&&&&&&&&&&&&&&& //response = br.readLine();&&&&
&&&&&&&&&&&&&&& response = response + readL&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& is.close();&&&
&&&&&&&&&&& br.close();&&&
&&&&&&&&&&& uRLConnection.disconnect();&&&
&&&&&&&&&&&&&&
&&&&&&& } catch (MalformedURLException e) {&&&
&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&&&&&&&&&
&&&&&&& } catch (IOException e) {&&&
&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&&&&&&&&&
&&&&&&& }&&&
String urlAddress = &http://192.168.1.102:8080/AndroidServer/login.do&;&
&&& HttpURLConnection uRLC&
&&& public UrlConnectionToServer(){&
&&& }&&&&& //向服务器发送get请求
&&& public String doGet(String username,String password){&
&&&&&&& String getUrl = urlAddress + &?username=&+username+&&password=&+&
&&&&&&& try {&
&&&&&&&&&&& url = new URL(getUrl);&
&&&&&&&&&&& uRLConnection = (HttpURLConnection)url.openConnection();&
&&&&&&&&&&& InputStream is = uRLConnection.getInputStream();&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&
&&&&&&&&&&& String response = &&;&
&&&&&&&&&&& String readLine =&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&
&&&&&&&&&&&&&&& //response = br.readLine();&
&&&&&&&&&&&&&&& response = response + readL&
&&&&&&&&&&& }&
&&&&&&&&&&& is.close();&
&&&&&&&&&&& br.close();&
&&&&&&&&&&& uRLConnection.disconnect();&
&&&&&&&&&&&&
&&&&&&& } catch (MalformedURLException e) {&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&&&&&&&
&&&&&&& } catch (IOException e) {&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&&&&&&&
&&&&&&& }&
&&&&&&&&& //向服务器发送post请求
&&& public String doPost(String username,String password){&
&&&&&&& try {&
&&&&&&&&&&& url = new URL(urlAddress);&
&&&&&&&&&&& uRLConnection = (HttpURLConnection)url.openConnection();&
&&&&&&&&&&& uRLConnection.setDoInput(true);&
&&&&&&&&&&& uRLConnection.setDoOutput(true);&
&&&&&&&&&&& uRLConnection.setRequestMethod(&POST&);&
&&&&&&&&&&& uRLConnection.setUseCaches(false);&
&&&&&&&&&&& uRLConnection.setInstanceFollowRedirects(false);&
&&&&&&&&&&& uRLConnection.setRequestProperty(&Content-Type&, &application/x-www-form-urlencoded&);&
&&&&&&&&&&& uRLConnection.connect();&
&&&&&&&&&&&&&
&&&&&&&&&&& DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());&
&&&&&&&&&&& String content = &username=&+username+&&password=&+&
&&&&&&&&&&& out.writeBytes(content);&
&&&&&&&&&&& out.flush();&
&&&&&&&&&&& out.close();&
&&&&&&&&&&&&&
&&&&&&&&&&& InputStream is = uRLConnection.getInputStream();&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&
&&&&&&&&&&& String response = &&;&
&&&&&&&&&&& String readLine =&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&
&&&&&&&&&&&&&&& //response = br.readLine();&
&&&&&&&&&&&&&&& response = response + readL&
&&&&&&&&&&& }&
&&&&&&&&&&& is.close();&
&&&&&&&&&&& br.close();&
&&&&&&&&&&& uRLConnection.disconnect();&
&&&&&&&&&&&&
&&&&&&& } catch (MalformedURLException e) {&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&&&&&&&
&&&&&&& } catch (IOException e) {&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&&&&&&&
&&&&&&& }&
HTTPClient
[java] String urlAddress = &http://192.168.1.102:8080/qualityserver/login.do&;&&&
public HttpClientServer(){&&&
&&&&&&&&&&&
public String doGet(String username,String password){&&&
&&& String getUrl = urlAddress + &?username=&+username+&&password=&+&&&
&&& HttpGet httpGet = new HttpGet(getUrl);&&&
&&& HttpParams hp = httpGet.getParams();&&&
&&& hp.getParameter(&true&);&&&
&&& //hp.&&&&
&&& //httpGet.setp&&&&
&&& HttpClient hc = new DefaultHttpClient();&&&
&&& try {&&&
&&&&&&& HttpResponse ht = hc.execute(httpGet);&&&
&&&&&&& if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){&&&
&&&&&&&&&&& HttpEntity he = ht.getEntity();&&&
&&&&&&&&&&& InputStream is = he.getContent();&&&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&&&
&&&&&&&&&&& String response = &&;&&&
&&&&&&&&&&& String readLine =&&&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&&&
&&&&&&&&&&&&&&& //response = br.readLine();&&&&
&&&&&&&&&&&&&&& response = response + readL&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& is.close();&&&
&&&&&&&&&&& br.close();&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& //String str = EntityUtils.toString(he);&&&&
&&&&&&&&&&& System.out.println(&=========&+response);&&&
&&&&&&&&&&&&&&
&&&&&&& }else{&&&
&&&&&&&&&&& return &error&;&&&
&&&&&&& }&&&
&&& } catch (ClientProtocolException e) {&&&
&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&& e.printStackTrace();&&&
&&&&&&& return &exception&;&&&
&&& } catch (IOException e) {&&&
&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&& e.printStackTrace();&&&
&&&&&&& return &exception&;&&&
&&& }&&&&&&&
public String doPost(String username,String password){&&&
&&& //String getUrl = urlAddress + &?username=&+username+&&password=&+&&&&
&&& HttpPost httpPost = new HttpPost(urlAddress);&&&
&&& List params = new ArrayList();&&&
&&& NameValuePair pair1 = new BasicNameValuePair(&username&, username);&&&
&&& NameValuePair pair2 = new BasicNameValuePair(&password&, password);&&&
&&& params.add(pair1);&&&
&&& params.add(pair2);&&&
&&& HttpE&&&
&&& try {&&&
&&&&&&& he = new UrlEncodedFormEntity(params, &gbk&);&&&
&&&&&&& httpPost.setEntity(he);&&&
&&&&&&&&&&&
&&& } catch (UnsupportedEncodingException e1) {&&&
&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&& e1.printStackTrace();&&&
&&& HttpClient hc = new DefaultHttpClient();&&&
&&& try {&&&
&&&&&&& HttpResponse ht = hc.execute(httpPost);&&&
&&&&&&& //连接成功&&&&
&&&&&&& if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){&&&
&&&&&&&&&&& HttpEntity het = ht.getEntity();&&&
&&&&&&&&&&& InputStream is = het.getContent();&&&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&&&
&&&&&&&&&&& String response = &&;&&&
&&&&&&&&&&& String readLine =&&&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&&&
&&&&&&&&&&&&&&& //response = br.readLine();&&&&
&&&&&&&&&&&&&&& response = response + readL&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& is.close();&&&
&&&&&&&&&&& br.close();&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& //String str = EntityUtils.toString(he);&&&&
&&&&&&&&&&& System.out.println(&=========&&&+response);&&&
&&&&&&&&&&&&&&
&&&&&&& }else{&&&
&&&&&&&&&&& return &error&;&&&
&&&&&&& }&&&
&&& } catch (ClientProtocolException e) {&&&
&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&& e.printStackTrace();&&&
&&&&&&& return &exception&;&&&
&&& } catch (IOException e) {&&&
&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&& e.printStackTrace();&&&
&&&&&&& return &exception&;&&&
&&& }&&&&&&
String urlAddress = &http://192.168.1.102:8080/qualityserver/login.do&;&
public HttpClientServer(){&
public String doGet(String username,String password){&
&&& String getUrl = urlAddress + &?username=&+username+&&password=&+&
&&& HttpGet httpGet = new HttpGet(getUrl);&
&&& HttpParams hp = httpGet.getParams();&
&&& hp.getParameter(&true&);&
&&& //hp.&
&&& //httpGet.setp&
&&& HttpClient hc = new DefaultHttpClient();&
&&& try {&
&&&&&&& HttpResponse ht = hc.execute(httpGet);&
&&&&&&& if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){&
&&&&&&&&&&& HttpEntity he = ht.getEntity();&
&&&&&&&&&&& InputStream is = he.getContent();&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&
&&&&&&&&&&& String response = &&;&
&&&&&&&&&&& String readLine =&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&
&&&&&&&&&&&&&&& //response = br.readLine();&
&&&&&&&&&&&&&&& response = response + readL&
&&&&&&&&&&& }&
&&&&&&&&&&& is.close();&
&&&&&&&&&&& br.close();&
&&&&&&&&&&&&&
&&&&&&&&&&& //String str = EntityUtils.toString(he);&
&&&&&&&&&&& System.out.println(&=========&+response);&
&&&&&&&&&&&&
&&&&&&& }else{&
&&&&&&&&&&& return &error&;&
&&&&&&& }&
&&& } catch (ClientProtocolException e) {&
&&&&&&& // TODO Auto-generated catch block&
&&&&&&& e.printStackTrace();&
&&&&&&& return &exception&;&
&&& } catch (IOException e) {&
&&&&&&& // TODO Auto-generated catch block&
&&&&&&& e.printStackTrace();&
&&&&&&& return &exception&;&
&&& }&&&&&
public String doPost(String username,String password){&
&&& //String getUrl = urlAddress + &?username=&+username+&&password=&+&
&&& HttpPost httpPost = new HttpPost(urlAddress);&
&&& List params = new ArrayList();&
&&& NameValuePair pair1 = new BasicNameValuePair(&username&, username);&
&&& NameValuePair pair2 = new BasicNameValuePair(&password&, password);&
&&& params.add(pair1);&
&&& params.add(pair2);&
&&& HttpE&
&&& try {&
&&&&&&& he = new UrlEncodedFormEntity(params, &gbk&);&
&&&&&&& httpPost.setEntity(he);&
&&& } catch (UnsupportedEncodingException e1) {&
&&&&&&& // TODO Auto-generated catch block&
&&&&&&& e1.printStackTrace();&
&&& HttpClient hc = new DefaultHttpClient();&
&&& try {&
&&&&&&& HttpResponse ht = hc.execute(httpPost);&
&&&&&&& //连接成功&
&&&&&&& if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){&
&&&&&&&&&&& HttpEntity het = ht.getEntity();&
&&&&&&&&&&& InputStream is = het.getContent();&
&&&&&&&&&&& BufferedReader br = new BufferedReader(new InputStreamReader(is));&
&&&&&&&&&&& String response = &&;&
&&&&&&&&&&& String readLine =&
&&&&&&&&&&& while((readLine =br.readLine()) != null){&
&&&&&&&&&&&&&&& //response = br.readLine();&
&&&&&&&&&&&&&&& response = response + readL&
&&&&&&&&&&& }&
&&&&&&&&&&& is.close();&
&&&&&&&&&&& br.close();&
&&&&&&&&&&&&&
&&&&&&&&&&& //String str = EntityUtils.toString(he);&
&&&&&&&&&&& System.out.println(&=========&&&+response);&
&&&&&&&&&&&&
&&&&&&& }else{&
&&&&&&&&&&& return &error&;&
&&&&&&& }&
&&& } catch (ClientProtocolException e) {&
&&&&&&& // TODO Auto-generated catch block&
&&&&&&& e.printStackTrace();&
&&&&&&& return &exception&;&
&&& } catch (IOException e) {&
&&&&&&& // TODO Auto-generated catch block&
&&&&&&& e.printStackTrace();&
&&&&&&& return &exception&;&
servlet端json转化:
[java]& resp.setContentType(&text/json&);&&&
&&&&&&& resp.setCharacterEncoding(&UTF-8&);&&&
&&&&&&& toDo = new ToDo();&&&
&&&&&&& List&UserBean& list = new ArrayList&UserBean&();&&&
&&&&&&& list = toDo.queryUsers(mySession);&&&
&&&&&&& S&&&
&&&&&&& //设定JSON&&&&
&&&&&&& JSONArray array = new JSONArray();&&&
&&&&&&& for(UserBean bean : list)&&&
&&&&&&& {&&&
&&&&&&&&&&& JSONObject obj = new JSONObject();&&&
&&&&&&&&&&& try&&&
&&&&&&&&&&& {&&&
&&&&&&&&&&&&&&&& obj.put(&username&, bean.getUserName());&&&
&&&&&&&&&&&&&&&& obj.put(&password&, bean.getPassWord());&&&
&&&&&&&&&&&& }catch(Exception e){}&&&
&&&&&&&&&&&& array.add(obj);&&&
&&&&&&& }&&&
&&&&&&& pw.write(array.toString());&&&
&&&&&&& System.out.println(array.toString());&
resp.setContentType(&text/json&);&
&&&&&&& resp.setCharacterEncoding(&UTF-8&);&
&&&&&&& toDo = new ToDo();&
&&&&&&& List&UserBean& list = new ArrayList&UserBean&();&
&&&&&&& list = toDo.queryUsers(mySession);&
&&&&&&& S&
&&&&&&& //设定JSON&
&&&&&&& JSONArray array = new JSONArray();&
&&&&&&& for(UserBean bean : list)&
&&&&&&& {&
&&&&&&&&&&& JSONObject obj = new JSONObject();&
&&&&&&&&&&& try&
&&&&&&&&&&& {&
&&&&&&&&&&&&&&&& obj.put(&username&, bean.getUserName());&
&&&&&&&&&&&&&&&& obj.put(&password&, bean.getPassWord());&
&&&&&&&&&&&& }catch(Exception e){}&
&&&&&&&&&&&& array.add(obj);&
&&&&&&& }&
&&&&&&& pw.write(array.toString());&
&&&&&&& System.out.println(array.toString());
[java]& String urlAddress = &http://192.168.1.102:8080/qualityserver/result.do&;&&&
&&&&&&& String body =&&&&
&&&&&&&&&&& getContent(urlAddress);&&&
&&&&&&& JSONArray array = new JSONArray(body);&&&&&&&&&&&&&
&&&&&&& for(int i=0;i&array.length();i++)&&&
&&&&&&& {&&&
&&&&&&&&&&& obj = array.getJSONObject(i);&&&
&&&&&&&&&&& sb.append(&用户名:&).append(obj.getString(&username&)).append(&\t&);&&&
&&&&&&&&&&& sb.append(&密码:&).append(obj.getString(&password&)).append(&\n&);&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& HashMap&String, Object& map = new HashMap&String, Object&();&&&
&&&&&&&&&&& try {&&&
&&&&&&&&&&&&&&& userName = obj.getString(&username&);&&&
&&&&&&&&&&&&&&& passWord = obj.getString(&password&);&&&
&&&&&&&&&&& } catch (JSONException e) {&&&
&&&&&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& map.put(&username&, userName);&&&
&&&&&&&&&&& map.put(&password&, passWord);&&&
&&&&&&&&&&& listItem.add(map);&&&
&&&&&&&&&&&&&&&
&&&&&&& }&&&
&&&&&&&&&&&
&&&&&&& } catch (Exception e) {&&&
&&&&&&&&&&& // TODO Auto-generated catch block&&&&
&&&&&&&&&&& e.printStackTrace();&&&
&&&&&&& }&&&
&&&&&&&&&&&
&&&&&&& if(sb!=null)&&&
&&&&&&& {&&&
&&&&&&&&&&& showResult.setText(&用户名和密码信息:&);&&&
&&&&&&&&&&& showResult.setTextSize(20);&&&
&&&&&&& } else&&&
&&&&&&&&&&& extracted();&&&
&&&&&& //设置adapter&&&&&
&&&&&&& SimpleAdapter simple = new SimpleAdapter(this,listItem,&&&
&&&&&&&&&&&&&&& android.R.layout.simple_list_item_2,&&&
&&&&&&&&&&&&&&& new String[]{&username&,&password&},&&&
&&&&&&&&&&&&&&& new int[]{android.R.id.text1,android.R.id.text2});&&&
&&&&&&& listResult.setAdapter(simple);&&&
&&&&&&&&&&&
&&&&&&& listResult.setOnItemClickListener(new OnItemClickListener() {&&&
&&&&&&&&&&& @Override&&&
&&&&&&&&&&& public void onItemClick(AdapterView&?& parent, View view,&&&
&&&&&&&&&&&&&&&&&&& int position, long id) {&&&
&&&&&&&&&&&&&&& int positionId = (int) (id+1);&&&
&&&&&&&&&&&&&&& Toast.makeText(MainActivity.this, &ID:&+positionId, Toast.LENGTH_LONG).show();&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&& }&&&
&&&&&&& });&&&
&&& private void extracted() {&&&
&&&&&&& showResult.setText(&没有有效的数据!&);&&&
&&& //和服务器连接&&&&
&&& private String getContent(String url)throws Exception{&&&
&&&&&&& StringBuilder sb = new StringBuilder();&&&
&&&&&&& HttpClient client =new DefaultHttpClient();&&&
&&&&&&& HttpParams httpParams =client.getParams();&&&
&&&&&&&&&&&
&&&&&&& HttpConnectionParams.setConnectionTimeout(httpParams, 3000);&&&
&&&&&&& HttpConnectionParams.setSoTimeout(httpParams, 5000);&&&
&&&&&&& HttpResponse response = client.execute(new HttpGet(url));&&&
&&&&&&& HttpEntity entity =response.getEntity();&&&
&&&&&&&&&&&
&&&&&&& if(entity !=null){&&&
&&&&&&&&&&& BufferedReader reader = new BufferedReader(new InputStreamReader&&&
&&&&&&&&&&&&&&&&&&& (entity.getContent(),&UTF-8&),8192);&&&
&&&&&&&&&&& String line =&&&
&&&&&&&&&&& while ((line= reader.readLine())!=null){&&&
&&&&&&&&&&&&&&& sb.append(line +&\n&);&&&
&&&&&&&&&&& }&&&
&&&&&&&&&&& reader.close();&&&
&&&&&&& }&&&
&&&&&&& return sb.toString();&&&
String urlAddress = &http://192.168.1.102:8080/qualityserver/result.do&;&
&&&&&&& String body =&&
&&&&&&&&&&& getContent(urlAddress);&
&&&&&&& JSONArray array = new JSONArray(body);&&&&&&&&&&&
&&&&&&& for(int i=0;i&array.length();i++)&
&&&&&&& {&
&&&&&&&&&&& obj = array.getJSONObject(i);&
&&&&&&&&&&& sb.append(&用户名:&).append(obj.getString(&username&)).append(&\t&);&
&&&&&&&&&&& sb.append(&密码:&).append(obj.getString(&password&)).append(&\n&);&
&&&&&&&&&&&&&
&&&&&&&&&&& HashMap&String, Object& map = new HashMap&String, Object&();&
&&&&&&&&&&& try {&
&&&&&&&&&&&&&&& userName = obj.getString(&username&);&
&&&&&&&&&&&&&&& passWord = obj.getString(&password&);&
&&&&&&&&&&& } catch (JSONException e) {&
&&&&&&&&&&&&&&& e.printStackTrace();&
&&&&&&&&&&& }&
&&&&&&&&&&& map.put(&username&, userName);&
&&&&&&&&&&& map.put(&password&, passWord);&
&&&&&&&&&&& listItem.add(map);&
&&&&&&&&&&&&&
&&&&&&& }&
&&&&&&& } catch (Exception e) {&
&&&&&&&&&&& // TODO Auto-generated catch block&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&& }&
&&&&&&& if(sb!=null)&
&&&&&&& {&
&&&&&&&&&&& showResult.setText(&用户名和密码信息:&);&
&&&&&&&&&&& showResult.setTextSize(20);&
&&&&&&& } else&
&&&&&&&&&&& extracted();&
&&&&&& //设置adapter&&
&&&&&&& SimpleAdapter simple = new SimpleAdapter(this,listItem,&
&&&&&&&&&&&&&&& android.R.layout.simple_list_item_2,&
&&&&&&&&&&&&&&& new String[]{&username&,&password&},&
&&&&&&&&&&&&&&& new int[]{android.R.id.text1,android.R.id.text2});&
&&&&&&& listResult.setAdapter(simple);&
&&&&&&& listResult.setOnItemClickListener(new OnItemClickListener() {&
&&&&&&&&&&& @Override&
&&&&&&&&&&& public void onItemClick(AdapterView&?& parent, View view,&
&&&&&&&&&&&&&&&&&&& int position, long id) {&
&&&&&&&&&&&&&&& int positionId = (int) (id+1);&
&&&&&&&&&&&&&&& Toast.makeText(MainActivity.this, &ID:&+positionId, Toast.LENGTH_LONG).show();&
&&&&&&&&&&&&&
&&&&&&&&&&& }&
&&&&&&& });&
&&& private void extracted() {&
&&&&&&& showResult.setText(&没有有效的数据!&);&
&&& //和服务器连接&
&&& private String getContent(String url)throws Exception{&
&&&&&&& StringBuilder sb = new StringBuilder();&
&&&&&&& HttpClient client =new DefaultHttpClient();&
&&&&&&& HttpParams httpParams =client.getParams();&
&&&&&&& HttpConnectionParams.setConnectionTimeout(httpParams, 3000);&
&&&&&&& HttpConnectionParams.setSoTimeout(httpParams, 5000);&
&&&&&&& HttpResponse response = client.execute(new HttpGet(url));&
&&&&&&& HttpEntity entity =response.getEntity();&
&&&&&&& if(entity !=null){&
&&&&&&&&&&& BufferedReader reader = new BufferedReader(new InputStreamReader&
&&&&&&&&&&&&&&&&&&& (entity.getContent(),&UTF-8&),8192);&
&&&&&&&&&&& String line =&
&&&&&&&&&&& while ((line= reader.readLine())!=null){&
&&&&&&&&&&&&&&& sb.append(line +&\n&);&
&&&&&&&&&&& }&
&&&&&&&&&&& reader.close();&
&&&&&&& }&
&&&&&&& return sb.toString();&

我要回帖

更多关于 九色腾类似的还有什么 的文章

 

随机推荐