HttpClient Restful Post 请求

    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;
    }

 

posted @ 2017-09-01 10:24  yshy  阅读(1845)  评论(0编辑  收藏  举报