httpClient访问http的rest接口

访问http的rest接口

1、get方式访问http的rest接口

    /**
     * 以get的方式访问http的rest接口
     * @param url
     * @return
     * @throws Exception
     */
      public static String httpGet(String url) throws Exception {  
        BufferedReader in = null;  
        String content = null;  
        try {  
            // 定义HttpClient  
            HttpClient client = new DefaultHttpClient();  
            // 实例化HTTP方法  
            HttpGet request = new HttpGet();  
            request.setURI(new URI(url));  
            HttpResponse response = client.execute(request);  

            in = new BufferedReader(new InputStreamReader(response.getEntity()  
                    .getContent()));  
            StringBuffer sb = new StringBuffer("");  
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while ((line = in.readLine()) != null) {  
                sb.append(line + NL);  
            }  
            in.close();  
            content = sb.toString();  
        } finally {  
            if (in != null) {  
                try {  
                    in.close();// 最后要关闭BufferedReader  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            return content;  
        }  
    }  

测试get方式的链接:http://localhost:7080/api/getUser?username=hello

    public static void main(String[] args) throws Exception {       
        String api = "http://localhost:7080/api";
        String content = HttpClientUtil.httpGet(api + "/getUser?username=hello" );
        System.out.println( content);
    }

2、post方式(json和表单)访问http的rest接口

1)json的形式post数据
Headers为:content-type:application/json
Body:{key1:value1, key2:value2, key3:value3}

    /**
     * 以json的形式提交数据
     * @param url
     * @param obj
     * @return
     */
    public static String httpPost(String url, JSONObject obj) {
        String _encoding = "UTF-8";
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(obj.toString(),"utf-8");//解决中文乱码问题    
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");    
            post.setEntity(entity);    
            System.out.println("getRequestLine:" + post.getRequestLine());

            // 执行请求
            HttpResponse response = client.execute(post);
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent(), _encoding));
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
            // 关闭连接.
            try {
                client.getConnectionManager().shutdown();
            } catch (Exception e1) {
            }
        }
        String str = "";
        try {
            str = sb.toString();
        } catch (Exception e) {

        }
        return str; 
    }

测试post json数据的链接 : http://localhost:7080/api/token
将数据存于JSONObject中

     public static void main(String[] args) throws Exception {      
        String api = "http://localhost:7080/api";
        String str = "{accessToken:'aa',expiresIn:7200,createTime:1234566,flag:1,appId:111111111}";
        JSONObject obj = JSONObject.fromObject(str);
        String content = HttpClientUtil.httpPost1(api + "/token" , obj);
        System.out.println( content);
    }

2)表单的形式post数据
Headers为:content-type:application/x-www-form-urlencoded; charset=UTF-8
Body:key=value

注意:post方式默认以表单的形式提交数据

    /**
     * 以表单的形式提交数据
     * @param url
     * @param params
     * @return
     */
    public static String httpPost(String url, List<NameValuePair> params) {
        String _encoding = "UTF-8";
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {

            //设置字符集
            post.setEntity(new UrlEncodedFormEntity(params,_encoding));

            // 执行请求
            HttpResponse response = client.execute(post);
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent(), _encoding));
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
            // 关闭连接.
            try {
                client.getConnectionManager().shutdown();
            } catch (Exception e1) {
            }
        }
        String str = "";
        try {
            str = sb.toString();
        } catch (Exception e) {

        }
        return str;
    }

测试post表单数据的链接 : http://localhost:7080/api/getToken?appId=111111111

    public static void main(String[] args) throws Exception {       
        String api = "http://localhost:7080/api";//测试的url
        //将需要使用的表单数据存于List<NameValuePair>
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("appId", "111111111"));
        String content = httpPost(api + "/getToken" , list);
        System.out.println( content);
    }
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值