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

httpClient使用post

时间:2019-07-06 16:16:59      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:sys   ret   erro   ica   ack   form   表单提交   public   pre   

/**
 * httpClient 发送表单提交的方式
*/
public static String sendPost(String url, String param)
{
    PrintWriter out = null;
    BufferedReader in = null;
    StringBuilder result = new StringBuilder();
    try
    {
        log.info("sendPost - {}", url+"/r/n"+param);
        URL realUrl = new 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)");
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("contentType", "utf-8");
        //通过form进行提交
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line;
        while ((line = in.readLine()) != null)
        {
            result.append(line);
        }
        log.info("recv - {}", result);
    }
    catch (ConnectException e)
    {
        log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
    }
    catch (SocketTimeoutException e)
    {
        log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
    }
    catch (IOException e)
    {
        log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
    }
    catch (Exception e)
    {
        log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
    }
    finally
    {
        try
        {
            if (out != null)
            {
                out.close();
            }
            if (in != null)
            {
                in.close();
            }
        }
        catch (IOException ex)
        {
            log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
        }
    }
    return result.toString();
}

/** 
* httpClient 发送表单接收的方式
*/
@ResponseBody
    @RequestMapping(value = {"/appCall"}, method = {RequestMethod.POST}, produces = {"text/html;charset=UTF-8"})
    public String appCall(HttpServletRequest request, HttpServletResponse response) {
        String responseStr = "";
        StringBuffer logStr = new StringBuffer();
        String jsonParam = request.getParameter("jsonParam");
        try {
            JSONObject obj = JSONObject.fromObject(jsonParam);
        } catch (Exception e) {
            System.out.println(e);
        }
        return jsonParam;
    }



/**
 * httpClient 发送内容体提交的方式
 */

public static String sendPostBody(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            log.info("sendPost - {}", url+"/r/n"+param);
            URL realUrl = new 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)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
     /**
     * 内容体接收
     */
    @ResponseBody
    @RequestMapping(value = {"/encryptAppCall"}, method = {RequestMethod.POST})
    public AppResult getAppCall(HttpServletRequest request, HttpServletResponse response) {
        AppResult appResult = new AppResult();
        try {
            String str = Utils.toBuffer(request);
            JSONObject obj = JSONObject.fromObject(str);
            return appResult;
        } catch (Exception e) {
            appResult.setReturn_code(1);
            appResult.setMessage("" + e);
            return appResult;
        }
    }
    /**
     * 从请求内容体中获取数据
     * @param request
     * @return
     */
    public static  String toBuffer(HttpServletRequest request) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = null;
        try {
            request.setCharacterEncoding("UTF-8");
            reader = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

 

httpClient使用post

标签:sys   ret   erro   ica   ack   form   表单提交   public   pre   

原文地址:https://www.cnblogs.com/zongguitao/p/11143013.html

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