httpClient访问http的rest接口

来源:互联网 发布:电脑桌面设置软件 编辑:程序博客网 时间:2024/04/29 11:33

访问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);    }
1 0
原创粉丝点击