直接代码:
package cn.itcast.crawler.test;
importorg.Apache.http.http entity;
importorg.Apache.http.client.methods.closeablehttpresponse;
importorg.Apache.http.client.methods.http get;
importorg.Apache.http.client.utils.uri builder;
importorg.Apache.http.impl.client.closeablehttpclient;
importorg.Apache.http.impl.client.http clients;
importorg.Apache.http.util.entity utils;
import java.io.IOException;
import Java.net.urisyntaxexception;
公共类httpgetparamtest {
publicstaticvoidmain (string [ ] args ) throws Exception { )。
//1 .创建http客户端对象
closeablehttpclienthttpclient=http clients.create default (;
//请求:设置请求的地址是http://yun.itheima.com/search? keys=java
创建URL构建器
uribuilderuribuilder=new uri builder (http://yun.it heima.com/search );
//设定参数
uribuilder.setparameter('keys )、' java );
创建//2.httpget对象并设置URL地址
http get http get=new http get (uri builder.build );
System.out.println;
//使用//http客户端启动响应并获取响应
closeablehttpresponseresponse=null;
try {
response=http client.execute (http get;
//4 .分析响应并获取数据
//判断状态代码是否为200
response.get statusline (.get status code ) (==200 ) )。
httpentityhttpentity=response.get entity (;
string content=entity utils.tostring (http entity,' utf8 ' );
system.out.println (content.length );
}
}catch(ioexceptione ) {
e .打印任务跟踪(;
}finally {
try {
response.close (;
}catch(ioexceptione ) {
e .打印任务跟踪(;
}
try {
httpClient.close (;
}catch(ioexceptione ) {
e .打印任务跟踪(;
}
}
}
}
执行结果:
从上面的结果可以看出,发送的是get请求,是参数
创建URL构建器
uribuilderuribuilder=new uri builder (http://yun.it heima.com/search );
//设定参数
uribuilder.setparameter('keys )、' java );
上面两行代码是带参数的主要代码,这是带一个参数的。 如果需要至少有两个参数,则代码可能如下所示:
uribuilder.setParameter('keys ),' java ) ).setparameter ),' );
直接加在后面就行了