**
关于httputil工具类
**
通过post方式请求链接,并返回响应结果
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
第二种post发送请求
public static String sendPost(String url){
HttpPost post = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
//启动执行请求,并获得返回值
CloseableHttpResponse execute = null;
try {
execute = client.execute(post);
HttpEntity entity = execute.getEntity();
//把实体对象转换为string
return EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return "调用失败";
}
通过post方法请求连接,并附带json格式的数据。并响应结果
我们先需要导入httpclirnt的jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
具体代码如下
public static String sendPostJson(JSONObject json,String URL) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result;
try {
StringEntity str = new StringEntity(json.toString(), "utf-8");
str.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(str);
// 发送请求
CloseableHttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
System.out.println("请求服务器成功");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
logger.error("请求异常:"+e.getMessage());
throw new RuntimeException(e);
}
return result;
}
通过get方式请求链接,并返回响应结果,需要传入地址和参数!
/**
* 向指定URL发送GET方法的请求
*
* @param url:发送请求的URL
* @param param:请求参数,请求参数应该是 name1=value1&name2=value2&name3=value3 的形式。
* @return String[result]:所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
使用Httpclient发送get请求
/**
* 通过httpclient发送get请求
* @param reqURL
* @return
* @throws IOException
*/
public static String sendGetRequest(String reqURL) throws IOException {
String responseContent = null; //响应内容
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); //创建org.apache.http.client.methods.HttpGet
HttpResponse response = httpClient.execute(httpGet); //执行GET请求
HttpEntity entity = response.getEntity(); //获取响应实体
if(null != entity){
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); //Consume response content
}
System.out.println(httpGet.getURI());
return responseContent;
}
通过get方式请求链接,并返回响应结果,需要传入地址!
/**
* 向指定URL发送GET方法的请求
*
* @param url:发送请求的URL
* @return String[result]:所代表远程资源的响应结果
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
// String urlNameString = url;
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
获取请求的ip地址
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
需要用到alibaba的fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
Post请求携带Json请求体
public static String sendPostJson(JSONObject json,String URL) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result;
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
CloseableHttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, StandardCharsets.UTF_8));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
System.out.println("请求服务器成功");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
logger.error("请求异常:"+e.getMessage());
throw new RuntimeException(e);
}
return result;
}
public static String sendPostJson2(JSONObject json,String URL) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type", "application/json");
String result;
try {
StringEntity s = new StringEntity(json.toJSONString(), StandardCharsets.UTF_8);
post.setEntity(s);
// 发送请求
CloseableHttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, StandardCharsets.UTF_8));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line).append("\n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
System.out.println("请求服务器成功");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
logger.error("请求异常:"+e.getMessage());
throw new RuntimeException(e);
}
return result;
}