PDMHttpClient发送post请求

http发送post请求


public class PDMHttpClient {
    private  final Logger logger = Logger.getLogger(PDMHttpClient.class);

    private String _accessToken;
    private Properties properties = new Properties();
    private String _BaseUrl = "http://localhost:9527/";
    private String _UserName  = "15219500267";
    private String _Password = "15219500267";

    private String _SynReply = "";
    private int _roleType = 1;


    RequestConfig _RequestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(30000).setSocketTimeout(60000).build();

    public PDMHttpClient(){
        try {
            properties.load(PDMHttpClient.class.getClassLoader().getResourceAsStream("./config/application.properties"));
            _BaseUrl = properties.getProperty("pdmbaseurl");//http://localhost:9527/
            _UserName = properties.getProperty("pdmusername");
            _Password = properties.getProperty("pdmpassword");
            _roleType = 1;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        }
    }

    public void login() {
        String requestUri = "auth/login";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(_BaseUrl + requestUri);
        try {
            String json = String.format(
                    "{\"username\":\"%s\",\"password\":\"%s\",\"roleType\":\"%s\"}",
                    _UserName, _Password,_roleType);
            StringEntity stringentity = new StringEntity(json, "utf-8");
            stringentity.setContentEncoding("UTF-8");
            stringentity.setContentType("application/json");
            httppost.setEntity(stringentity);
            httppost.setConfig(_RequestConfig);

            // HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
            // RequestConfig config =
            // RequestConfig.custom().setProxy(proxy).build();
            // httppost.setConfig(config);

            logger.info("login request: " + httppost.getURI() + ", parameter: " + json);
            CloseableHttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String value = EntityUtils.toString(entity, "UTF-8");
            logger.info("login result: " + value);
            HashMap<String, String> o = (HashMap<String, String>)JsonUtil.parseObject(value, HashMap.class);
            _accessToken = o.get("token");

            logger.info("login token: " + _accessToken);

        } catch (ClientProtocolException e) {
            logger.error(e);
        } catch (UnsupportedEncodingException e1) {
            logger.error(e1);
        } catch (IOException e) {
            logger.error(e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }


    public String post(String requestUri, Object parameter) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(_BaseUrl + requestUri);
        try {
            String json = JsonUtil.toJSON(parameter);
            StringEntity stringentity = new StringEntity(json, "utf-8");
            stringentity.setContentEncoding("UTF-8");
            stringentity.setContentType("application/json");
            httppost.setEntity(stringentity);
            httppost.setHeader("token",_accessToken);
            httppost.setConfig(_RequestConfig);

            // HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
            // RequestConfig config =
            // RequestConfig.custom().setProxy(proxy).build();
            // httppost.setConfig(config);

            logger.info("post request: " + httppost.getURI() + ", parameter: " + json);
            CloseableHttpResponse response = httpclient.execute(httppost);
            logger.info("post status: " + response.getStatusLine().getStatusCode());
            try {
                if (response.getStatusLine().getStatusCode() == 200
                        || response.getStatusLine().getStatusCode() == 403) {
                    HttpEntity htttpentity = response.getEntity();
                    String value = EntityUtils.toString(htttpentity, "UTF-8");
                    logger.info("post result: " + value);
                    return value;
                }else {
                    return String.valueOf(response.getStatusLine().getStatusCode());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            logger.error(e);
        } catch (UnsupportedEncodingException e1) {
            logger.error(e1);
        } catch (IOException e) {
            logger.error(e);
        } catch (Exception e) {
            logger.error(e);
        } catch (Throwable e) {
            logger.error(e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        return null;
    }

    public <T> MessageInfo<T> excute(Callable<T> func) {
        MessageInfo<T> mi = new MessageInfo<T>();
        try {
            mi.setData(func.call());
            mi.setIsSuccess(true);
        } catch (Exception e) {
            logger.error(e);
            mi.setIsSuccess(false);
            mi.setMessage(e.getMessage());
        }
        return mi;
    }

    public String view(String number) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Number", number);
        String response = post("system/material/findAll", jsonObj);
        return response;
    }
//    public String view() {
//        String response = post("system/material/findAll",null);
//        return response;
//    }

    public List<Material> view() {
//            String response = view(number);
//            String response = view();
            String response = post("system/material/findAll",null);
//            ViewResponseResult<T> data = JSON.parseObject(response, type);
            if(response.equals("500") || response.equals("404") || response.equals("301") || response.equals("401")){
                throw new IllegalArgumentException("数据检验失败,请重新提交");
            }
            List<Material> materials = JSONObject.parseArray(response, Material.class);
            if (materials == null) {
                return null;
            }
            return  materials;
    }


    private String getProductCodeResponse(String productcode) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("productCode", productcode);
        String response = post("system/product_code/list", jsonObj);
        return response;
    }


    public List<ProductCodeBase> getProdcutCode(String productcode) {
        String response = getProductCodeResponse(productcode);
        List<ProductCodeBase> productCodeBaseList = JSONObject.parseArray(response, ProductCodeBase.class);
        return productCodeBaseList;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值