您的位置:首页 > 理论基础 > 计算机网络

java模拟HTTP请求,发送JSON数据

2018-03-09 10:14 501 查看
1.使用HttpClient实现POST、GET请求的发送
2.举例
/**
*测试类
*/
public class Test{
    public static void main(String[] args){
        User u=new User();
         u.setUserName="张三";

         u.setUserPassWorld="zs123321";

         Map<String,String> params = new HashMap<String,String>();
    params.put("data",JSON.toJSONString(u));

         String result_ = HttpClientUtils.sendHttpMethod(url, params, "post");

         if(StringUtils.isNotBlank()){
            UserResult resultObject=JSON.parseObject(result_,UserResult.class);

            if(resultObject!=null){
              System.out.println("登陆结果:"+resultObject.getStatus);

            }

        }

     }
}
/**
*Http请求工具类
*/
public class HttpClientUtils{
    //单例 HttpClient 对象
private static HttpClient httpClient = null;

    //返回 HttpClient 单个实例
public static HttpClient getInstance() {
if (httpClient == null) {
httpClient = new HttpClient();
//RFC_2109是支持较普遍的一个,还有其他cookie协议
httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
}
return httpClient;
}

    public static String sendHttpMethod(String url,Map<String,String> params,String method){
String returnValue = "";

HttpClient client = HttpClientUtils.getInstance();
                           if("get".equals(method)){
StringBuffer p = null;
if(params!=null&¶ms.size()>0){
p = new StringBuffer();
for (String key : params.keySet()) {
p.append(key+"="+params.get(key)+"&") ;
}
}
if(p!=null&&p.length()>0){
url = url + p.substring(0,p.length()-1);
}
GetMethod method_get = getMethod(url);
int status;
try {
//指定传送字符集为UTF-8格式  
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
status = client.executeMethod(method_get);
if(status == 200){
returnValue = method_get.getResponseBodyAsString();
}
} catch (Exception e) {
System.out.println(url+"调用失败......");
}
}else if ("post".equals(method)) {
List<NameValuePair> params_ = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
params_.add(new NameValuePair(key,params.get(key)));
}
try {
returnValue = sendPostInfo(params, gateWay);
System.out.println(returnValue);
} catch (Exception e) {
System.out.println(url+"调用失败......");
}
}
return result;
}
    //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https
public static GetMethod getMethod(String url) {
GetMethod getMethod = new GetMethod(url);
//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
       new DefaultHttpMethodRetryHandler()); 
return getMethod;

}
    public static List<NameValuePair> buildRequestPara(
List<NameValuePair> sArray) {

// 除去数组中的空值
        List<NameValuePair> result = new ArrayList<NameValuePair>();
         if (sArray == null || sArray.size() <= 0) {
               return result;
           }
           for (NameValuePair nameValuePair : sArray) {
                String value = nameValuePair.getValue();
                if (value == null || value.equals("") 
                    || nameValuePair.getName().equalsIgnoreCase("sign_type")) {
                   continue;
               }
               result.add(new NameValuePair(nameValuePair.getName(), value));
          }
           return result;

}
    /**
* 构造模拟远程HTTP的POST请求,获取处理结果

* @param sParaTemp
*            请求参数数组
* @param gateway
*            网关地址
* @return 处理结果
* @throws Exception
*/
public static String sendPostInfo(List<NameValuePair> sParaTemp,
String gateway) throws Exception {
// 待请求参数数组
List<NameValuePair> sPara = buildRequestPara(sParaTemp);
HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
HttpRequest request = new HttpRequest(HttpResultType.BYTES);
// 设置编码集
request.setCharset("utf-8");
request.setParameters(generatNameValuePair(sPara));
request.setUrl(gateway);
HttpResponse response = httpProtocolHandler.execute(request);
if (response == null) {
return null;
}
String strResult = response.getStringResult();
return strResult;

}
    private static NameValuePair[] generatNameValuePair(
List<NameValuePair> properties) {
NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
int i = 0;
for (NameValuePair nvp : properties) {
nameValuePair[i++] = new NameValuePair(nvp.getName(),
nvp.getValue());
}
return nameValuePair;
}

}

/**
* HttpProtocolHandler 是模拟HTTP请求的核心类,最主要的是execute这个执行HTTP请求的方法
*/
public class HttpProtocolHandler {
private static String DEFAULT_CHARSET = "utf-8";
/** 连接超时时间,由bean factory设置,缺省为8秒钟 */
private int defaultConnectionTimeout = 8000;
/** 回应超时时间, 由bean factory设置,缺省为60秒钟 */
private int defaultSoTimeout = 2 * 60000;
/** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */
private int defaultIdleConnTimeout = 60000;
private int defaultMaxConnPerHost = 30;
private int defaultMaxTotalConn = 80;
/** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒 */
private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
/**
* HTTP连接管理器,该连接管理器必须是线程安全的.
*/
private HttpConnectionManager connectionManager;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();

/**
* 工厂方法

* @return
*/
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}

/**
* 私有的构造方法
*/
private HttpProtocolHandler() {
// 创建一个线程安全的HTTP连接池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(
defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(
defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}

/**
* 执行Http请求

* @param request
* @return
*/
public HttpResponse execute(HttpRequest request) {
HttpClient httpclient = new HttpClient(connectionManager);
// 设置连接超时
int connectionTimeout = defaultConnectionTimeout;
if (request.getConnectionTimeout() > 0) {
connectionTimeout = request.getConnectionTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setConnectionTimeout(connectionTimeout);
// 设置回应超时
int soTimeout = defaultSoTimeout;
if (request.getTimeout() > 0) {
soTimeout = request.getTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setSoTimeout(soTimeout);
// 设置等待ConnectionManager释放connection的时间
httpclient.getParams().setConnectionManagerTimeout(
defaultHttpConnectionManagerTimeout);
String charset = request.getCharset();
charset = charset == null ? DEFAULT_CHARSET : charset;
HttpMethod method = null;
if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
method = new GetMethod(request.getUrl());
method.getParams().setCredentialCharset(charset);
// parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
method.setQueryString(request.getQueryString());
} else {
method = new PostMethod(request.getUrl());
((PostMethod) method).addParameters(request.getParameters());
method.addRequestHeader("Content-Type",
"application/x-www-form-urlencoded; text/html; charset="
+ charset);
}
// 设置Http Header中的User-Agent属性
method.addRequestHeader("User-Agent", "Mozilla/4.0");
HttpResponse response = new HttpResponse();
try {
httpclient.executeMethod(method);
if (request.getResultType().equals(HttpResultType.STRING)) {
response.setStringResult(method.getResponseBodyAsString());
} else if (request.getResultType().equals(HttpResultType.BYTES)) {
response.setByteResult(method.getResponseBody());
}
response.setResponseHeaders(method.getResponseHeaders());
} catch (UnknownHostException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (Exception ex) {
return null;
} finally {
method.releaseConnection();
}
return response;
}

}
未完待续....
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: