首页 > Web开发 > 详细

HttpClient Restful Post 请求

时间:2017-09-01 10:31:43      阅读:282      评论:0      收藏:0      [点我收藏+]
    public static void main(String[] args) {
        SbVo sb = new SbVo();
        sb.setBusiness("SB");
        sb.setIphone("123456789");
        
        String param = new Gson().toJson(sb);
        String url = "http://127.0.0.1:9001/ssfwpt/sb/test";
        
        System.out.println(httpPost(url, param));
    }

    public static String httpPost(final String url, final String param) {
        String result = null;
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        postRequest.addHeader("Content-type", "application/json");

        try {
            StringEntity input = new StringEntity(param);

            input.setContentType("application/json");
            
            postRequest.setEntity(input);

            HttpResponse response = httpClient.execute(postRequest);
            
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Httpclienttest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Httpclienttest.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            httpClient.getConnectionManager().shutdown();
        }

        return result;
    }

 

HttpClient Restful Post 请求

原文:http://www.cnblogs.com/yshyee/p/7461969.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!