请注意!我使用的是httpclient4.5.3,如果是比较旧的版本可能会不支持。
我这里是使用maven来构建项目,用普通工程的请下载相关的包后加入buildpath 。
新建一个maven工程,选择勾选建立一个简单工程,点击完成。(不会的请百度一下下,用eclipse建立一个maven工程还是很简单的)
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
在工程pom.xm中加入上面的依赖log4j是用来打日志的,可以不加用普通的输出代替日志就行了。
下面直接贴代码
package newrank.com;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class HttpClientUtil {
protected static Logger logger = Logger.getLogger(HttpClientUtil.class);
public static CookieStore cookieStore = new BasicCookieStore();
public static CloseableHttpClient httpCilent = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
public static String httpPost(String url, List<BasicNameValuePair> list) {
// 配置超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
.setSocketTimeout(1000).setRedirectsEnabled(true).build();
HttpPost httpPost = new HttpPost(url);
// 设置超时时间
httpPost.setConfig(requestConfig);
String strResult = "";
int StatusCode=404;
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
// 设置post求情参数
httpPost.setEntity(entity);
HttpResponse httpResponse = httpCilent.execute(httpPost);
if (httpResponse != null) {
StatusCode=httpResponse.getStatusLine().getStatusCode();
if (httpResponse.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(httpResponse.getEntity());
logger.info("post/"+StatusCode+":"+strResult);
return strResult;
} else {
strResult = "Error Response: " + httpResponse.getStatusLine().toString();
logger.info("post/"+StatusCode+":"+strResult);
strResult=null;
}
} else {
}
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
}
return strResult;
}
public static String HttpGet(String url) {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
.build();
HttpGet httpGet2 = new HttpGet(url);
httpGet2.setConfig(requestConfig);
String srtResult =null;
int StatusCode=404;
try {
HttpResponse httpResponse = httpCilent.execute(httpGet2);
StatusCode=httpResponse.getStatusLine().getStatusCode();
if (httpResponse.getStatusLine().getStatusCode() == 200) {
srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
logger.info("get/"+StatusCode+":"+srtResult);
return srtResult;
} else {
srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
logger.info("get/"+StatusCode+":"+srtResult);
return null;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
public static void setCookieStore(List<BasicClientCookie> cookielist ) {
for(BasicClientCookie cookie:cookielist){
HttpClientUtil.cookieStore.addCookie(cookie);
}
}
public static void createCookie(List<BasicClientCookie> cookielist ) {
for(BasicClientCookie cookie:cookielist){
HttpClientUtil.cookieStore.addCookie(cookie);
}
}
}
这里整个过程都是用同一个httpCilent,主要是为了能让它像浏览器一样可以直接缓存Cookie信息,在登录接口调用后,不会导致有拦截登录的问题。但是如果有些是采用js写入的而不是在服务端写入的,需要根据前面返回的tooken等登录信息手动创建
Cookie并放到Cookie里面去。
如下面用到了JSONObject,请引入相关的包依赖pom.xml,这里我用的是2.4,注意依赖不要写错,官网上的写法是不指定jdk的,我们要自己加上,不然会报错。
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
下面给出 一些调用例子,具体业务需要你们自己写上面的方法只是给大家调用的。(新榜模拟登陆成功)
public static void login (){
List<BasicNameValuePair> list=getParam();
String loginUrl=NewrankConfig.URL_ROOT+NewrankConfig.URL_LOGIN;
String LoginResponse=HttpClientUtil.httpPost(loginUrl, list);
if(LoginResponse==null){
logger.error("登录没有返回");
return ;
}
JSONObject json = JSONObject.fromObject(LoginResponse);
Object success=json.get("success");
if(!(boolean)success){
logger.error("登录失败:"+json);
return ;
}
JSONObject value = json.getJSONObject("value");
XinbangUser ben = (XinbangUser) JSONObject.toBean(value, XinbangUser.class);
setCookieStore(ben);
}
public static void setCookieStore(XinbangUser ben) {
BasicClientCookie cookie = new BasicClientCookie("token", ben.getToken());
cookie.setDomain("www.newrank.cn");
cookie.setPath("/");
cookie.setVersion(0);
HttpClientUtil.cookieStore.addCookie(cookie);
}
最后
以上就是贤惠朋友最近收集整理的关于httpclient4.5.3 使用的全部内容,更多相关httpclient4.5.3内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复