利用apache包请求get和post请求,用户名和密码认证,用户名密码填则认证,不填测不认证
利用maven构建项目 需要导入一个包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
package com.fashion.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ......................................
* .没有才怎么怀才不遇,没有志怎么壮志难酬 .
* . ....................................
*
*@Author: lq
*@Date: 2018/10/10 14:21
*@Description: http pos请求
*/
public class HttpUtil {
public static String post(String url,Object obj,String userName,String password,String headType) {
//此处添加账号和密码
CredentialsProvider credentialsProvider = null;
if (userName != null && password !=null) {
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(getHost(url),AuthScope.ANY_PORT)
,new UsernamePasswordCredentials(userName,password));
}
CloseableHttpClient httpClient = null;
String content = null;
try {
//设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000)
.setConnectionRequestTimeout(600000).build();
// httpClient实例.
httpClient = HttpClients.custom() //此处可以添加权限
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.build();
//创建Http post请求
HttpPost httpPost = new HttpPost(url);
//设置请求头 可以设置多个
// Map<String,Object> headParams = new HashMap<>();
// headParams.put("Content-Type", "text/plain");
if (headType == null) {
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
}else {
httpPost.addHeader("Content-Type", "text/plain");
}
//设置请求主体
if (obj != null) {
StringEntity body = null;
if (obj instanceof String || obj instanceof JSONObject) {
body = new StringEntity(obj.toString(),"UTF-8");
}else {
body = new StringEntity(JSON.toJSONString(obj),"UTF-8");
}
httpPost.setEntity(body);
}
// 执行请求
final long beginTime = System.currentTimeMillis();
// http响应结果
CloseableHttpResponse response = httpClient.execute(httpPost);
//log.info("Http request completed Url:{},spend time{} ",url,System.currentTimeMillis() - beginTime);
//jsonObject.put("Code",response.getStatusLine().getStatusCode());
//得到请求主体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
content = EntityUtils.toString(responseEntity);
}
System.out.println("当前花费时间:【"+ (System.currentTimeMillis() - beginTime) + "】毫秒");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
/**
* 发送get请求
* @param url
* @return
*/
public static String sendGet(String url) {
String content = "";
// 创建 httpclient 对象
HttpClient httpclient = HttpClients.custom().build();
//创建请求方式,因为是get请求,所以可以在url后面连接请求参数
HttpGet httpget= new HttpGet(url);
try{
// 执行请求,获取响应数据
HttpResponse response = httpclient.execute(httpget);
// 获取请求实体,
HttpEntity responseEntity = response.getEntity();
// 获取返回实例的内容的长度
long len= responseEntity.getContentLength();
// 获取 content type
Header head= responseEntity.getContentType();
String bodys= head.toString();
System.out.println("内容长度"+len +"head 内容"+bodys);
//实例流的获取
if (responseEntity != null) {
content = EntityUtils.toString(responseEntity);
InputStream input = responseEntity.getContent();
byte []buffer= new byte[2048];
input.read(buffer);
String body= new String(buffer,"utf-8");
JSONObject json = JSONObject.parseObject(body);
}
}catch(Exception e){
e.printStackTrace();
}finally{
httpget.releaseConnection();
}
return content;
}
public static String getHost(final String url) {
if (url == null || "".equals(url.trim())) {
return "";
}
String host = "";
final Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
final Matcher matcher = p.matcher(url);
if (matcher.find()) {
host = matcher.group();
}
return host;
}
2.参数说明
用户名和密码传则有认证没有则不认证
headType默认是json格式
3.测试