如何从android程序调用Assembla REST apis

时间:2011-08-18 16:02:34

标签: android

我想从android中的代码中调用assembla apis。 我能够使用下面给出的代码连接到assembla,我以HTMl形式获得输出。 但无法理解如何使用这些数据。

代码片段:

HttpURLConnection conn = null;         试试{

        String authentication = "username:password";
        String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
        URL url = new URL("https://www.assembla.com/spaces/my_spaces");
        //URL url = new URL("https://www.assembla.com/");
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Authorization", "Basic " + encoding);
         conn.setDoOutput(true);
         conn.connect();

        System.out.println(conn.getResponseCode()); 
        System.out.println(conn.getResponseMessage());

        InputStreamReader isr =
            new InputStreamReader(conn.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = br.readLine()) != null)
            System.out.println(inputLine);

        br.close();

我对android很新,所以不知道我用来调用rest api的方法是否正确。 请指教。

感谢。

1 个答案:

答案 0 :(得分:0)

这就是我主要提出api请求的方式。

        HttpClient c = new DefaultHttpClient();
        HttpPost post = new HttpPost("URL");

        post.addHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        List<NameValuePair> httpparams = new ArrayList<NameValuePair>();

        httpparams.add(new BasicNameValuePair("password", password));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(httpparams);
        post.setEntity(entity);

        HttpResponse resp = c.execute(post);


        InputStream i = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(ir);

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        ir.close();
        br.close();

        JSONObject user = new JSONObject(sb.toString());

您可以根据需要添加或删除参数。 我假设你收到一个JSON对象(sb.toString())

编辑:在这种情况下,它是一个POST,您可以轻松将其更改为GET(HttpGet)