码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient 发送 POST 请求

时间:2016-05-12 23:36:54      阅读:370      评论:0      收藏:0      [点我收藏+]

标签:

API 说明

HttpClientBuilder用于创建CloseableHttpClient实例。
在 HttpClient 新的版本中, AbstractHttpClient、 AutoRetryHttpClient、 DefaultHttpClient等都被弃用了,使用HttpClientBuilder代替。

Client 代码

package com.bilfinance.core.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.achievo.framework.exception.FrameworkException;
import com.bilfinance.core.model.AsParam;
import com.bilfinance.core.model.AsResult;
import com.bilfinance.core.service.IAsHttpInterficeService;

@Service
public class AsHttpInterficeService implements IAsHttpInterficeService {

    private static Logger logger = LoggerFactory.getLogger(AsHttpInterficeService.class);


    @Override
    public AsResult doAsHttpMethod(AsParam asParam) throws FrameworkException {
        //请求内容
        String content = JSONObject.fromObject((Object)asParam).toString();
        logger.debug("AsParam = "+content);
        byte[] byte_content = null;
        try {
            byte_content = content.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e2) {
            throw new FrameworkException("请求参数字符集编码异常:Charset=UTF-8");
        }

        //建立连接
        String urlstr = "http://localhost:7070/bqjrcar/WeiXinServlet";
        logger.debug("URL = "+urlstr);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(urlstr);
        post.setConfig(RequestConfig.DEFAULT);
        EntityBuilder enbu = EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setContentEncoding("UTF-8").setBinary(byte_content);
        HttpEntity rqEntity = enbu.build();
        post.setEntity(rqEntity);

        //执行请求
        HttpResponse httprs = null;
        try {
            httprs = client.execute(post);
        } catch (IOException e) {
            throw new FrameworkException("请求失败。meg="+e.getMessage(),e);
        }
        HttpEntity rsEntity = httprs.getEntity();
        logger.debug("StatusLine = "+httprs.getStatusLine());

        //返回结果
        AsResult result = null;
        if(httprs.getStatusLine().getStatusCode() != 200)
            throw new FrameworkException("安硕系统异常,StatusLine="+httprs.getStatusLine());
        if(rsEntity==null) 
            throw new FrameworkException("安硕保存返回空");
        try {
            String text = EntityUtils.toString(rsEntity, "UTF-8");
            logger.debug("AsResult = "+text);
            result = (AsResult)JSONObject.toBean(JSONObject.fromObject(text), AsResult.class);
        } catch (ParseException | IOException e) {
            throw new FrameworkException("安硕返回字符集编码异常:Charset=UTF-8");
        }

        //关闭连接
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }


}

Servlet 代码

package com.weixinservlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amarsoft.are.ARE;

import net.sf.json.JSONObject;

public class WeiXinServlet extends HttpServlet{

    private static final long serialVersionUID = -3501685878733962236L;


    @Override
    protected void service(HttpServletRequest rq, HttpServletResponse rs) throws ServletException, IOException {
        AsParam param = getPostParameter(rq);
        AsResult result = new AsResult();

        //合同保存
        if(AsParam.method_saveBC.equals(param.getMethod())){
            try {
                result = new WeiXinSaveCreditInfo().saveCreditInfo(param);
                result.setStatus(AsResult.status_success);
            } catch (Exception e) {
                result.setStatus(AsResult.status_failed);
                result.setMessage(e.getMessage());
            }
        }else {
            result.setStatus(AsResult.status_failed);
            result.setMessage("方法名称不正确,method="+param.getMethod());
        }

        //设置 Response
        rs.setContentType("text/html; charset=utf-8");
        rs.setCharacterEncoding("UTF-8");
        String asResult = JSONObject.fromObject(result).toString();
        ARE.getLog().debug("AsResult = "+asResult);
        rs.getWriter().println(asResult);
    }


    /**
     * 获取request参数
     */
    private AsParam getPostParameter(HttpServletRequest request){
        StringBuffer sb = new StringBuffer();
        try {
            InputStream in = request.getInputStream();
            BufferedReader breader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
            String strTem;
            while((strTem=breader.readLine())!=null)
                sb.append(strTem); 
            breader.close();

            ARE.getLog().debug("AsParam = "+sb.toString());
            JSONObject datas = JSONObject.fromObject(sb.toString());
            AsParam bean = (AsParam)JSONObject.toBean(datas, AsParam.class);
            return bean;
        } catch (Exception e) {
            throw new RuntimeException("参数JSON格式错误!request="+sb.toString(),e);
        }
    }
}

AsParam.java

package com.weixinservlet;

import java.io.Serializable;
import java.util.HashMap;

public class AsParam implements Serializable{

    private static final long serialVersionUID = 1063546577762134098L;
    public static final String method_saveBC = "SaveCreditInfo"; 
    private String method;
    private String message;
    private HashMap<String, Object> data;
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public HashMap<String, Object> getData() {
        return data;
    }
    public void setData(HashMap<String, Object> data) {
        this.data = data;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

}

AsResult.java

package com.weixinservlet;

import java.io.Serializable;
import java.util.HashMap;

public class AsResult implements Serializable{

    private static final long serialVersionUID = -6044201397210634459L;
    public static final String status_success = "SUCCESS";
    public static final String status_failed = "FAILED";

    private String status;
    private String message;
    private HashMap<String, Object> data;

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public HashMap<String, Object> getData() {
        return data;
    }
    public void setData(HashMap<String, Object> data) {
        this.data = data;
    }

}

HttpClient 发送 POST 请求

标签:

原文地址:http://blog.csdn.net/tajun77/article/details/51346803

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!