博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http的get post 请求工具类
阅读量:7263 次
发布时间:2019-06-29

本文共 7116 字,大约阅读时间需要 23 分钟。

HttpClientUtil

 

package com.angular.base.util.httpUtil;

 

import java.io.IOException;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

 

import javax.servlet.http.HttpServletRequest;

 

import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

 

/*
* 执行http请求的java方法 下面提供GET 和 POST 请求 参数是以Map形式和jSON的格式
*
* */
public class HttpClientUtil {

 

/**
* 获取HttpServletRequest;
*
* @return [参数说明]
*
* @return HttpServletRequest [返回类型说明]
* @exception throws
* [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static HttpServletRequest getHttpRequest()
{
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 返回用户的IP地址
*
* @param request
* @return
*/
public static String toIpAddr(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;
}
public static String doGet(String url, Map<String, String> param) {

 

// 创建Httpclient对象

CloseableHttpClient httpclient = HttpClients.createDefault();

 

String resultString = "";

CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();

 

// 创建http GET请求

HttpGet httpGet = new HttpGet(uri);

 

// 执行请求

response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

 

public static String doGet(String url) {

return doGet(url, null);
}

 

//post请求 请求的url content请求体 contentType 请求体类型 --ContentType.APPLICATION_JSON -ContentType.APPLICATION_XML

public static String doPost(String url,String content,String contentType) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 模拟表单
StringEntity entity = new StringEntity(content,contentType);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return resultString;

}

}

 

HttpParam :

package com.angular.base.util.httpUtil;/* * http请求参数的封装类 * @Author:方伟林 * @Time:2016/12/27 * */public class HttpParam {     private String key;   // 请求参数       private String value; // 参数值       public HttpParam() {}       public HttpParam(String key, String value) {           this.key = key;           this.value = value;         }              public String getKey() {          return key;        }             public void setKey(String key) {           this.key = key;         }               public String getValue() {           return value;         }                public void setValue(String value) {          this.value = value;         }  }

HttpParamOperation :

package com.angular.base.util.httpUtil;import java.net.URLEncoder;import java.util.List;import java.util.Map;import org.apache.commons.lang3.StringUtils;import org.apache.log4j.Logger;/* * http请求参数的格式化、下面提供了两种方法 一个map  还有一个是基于httpParam类 * @Author:方伟林 * @Time:2016/12/27 * */public class HttpParamOperation {     private HttpParamOperation() {}         private static Logger logger = Logger.getLogger(HttpParamOperation.class.getName());               /**         * Created by fangweilin on 16/12/27         * @use 将map转换成url参数格式: name1=value1&name2=value2         * @param map 参数map         * @return String 返回参数格式: name1=value1&name2=value2         */         public static String getUrlParamsFromMap(Map
map) throws Exception { try { if (null != map) { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry
entry : map.entrySet()) { stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&"); } String content = stringBuilder.toString(); if (content.endsWith("&")) { content = StringUtils.substringBeforeLast(content, "&"); } return content; } } catch (Exception e) { logger.error(e); } return null; } /** * Created by fangweilin on 16/12/27 * @use 将HttpParam列表转换成url参数格式: name1=value1&name2=value2 * @param httpParamList HttpParam列表 * @return String 返回参数格式: name1=value1&name2=value2 */ public static String getUrlParamsFromList(List
httpParamList) throws Exception { try { if (null != httpParamList) { StringBuilder stringBuilder = new StringBuilder(); if (httpParamList.size() > 0) { for (HttpParam httpParam : httpParamList) { stringBuilder.append(URLEncoder.encode(httpParam.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(httpParam.getValue(), "UTF-8")).append("&"); } String content = stringBuilder.toString(); if (content.endsWith("&")) { content = StringUtils.substringBeforeLast(content, "&"); } return content; } } } catch (Exception e) { logger.error(e); } return null; } }

 

转载于:https://www.cnblogs.com/fangweilin/p/8507882.html

你可能感兴趣的文章
IN、EXISTS的相关子查询用INNER JOIN 代替--性能优化
查看>>
Java基础(三):修饰符、运算符、循环结构和分支结构
查看>>
聊聊手游的那些惊喜与惊吓
查看>>
hdu4901The Romantic Hero
查看>>
C#读写txt文件的两种方法介绍
查看>>
P2421 A-B数对(增强版)
查看>>
<html>
查看>>
linux下的抓包工具tcpdump
查看>>
因默认包扫描问题导致的SpringBoot项目无法启动问题
查看>>
Redis3.2.4 Cluster集群搭建
查看>>
Android中实现静态的默认安装和卸载应用
查看>>
Java常用排序算法及性能测试集合
查看>>
转载【小程序】: 微信小程序开发---应用与页面的生命周期
查看>>
如何在IDEA里给大数据项目导入该项目的相关源码(博主推荐)(类似eclipse里同一个workspace下单个子项目存在)(图文详解)...
查看>>
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字...
查看>>
Fiddler filter 过滤隐藏css、js、图片等
查看>>
parity 钱包
查看>>
JDBC优化策略总结
查看>>
Javascript -- document的createDocumentFragment()方法
查看>>
[转]bootstrap-datetimepicker 火狐浏览器报错
查看>>