2

AsanaAPIで遊んでいます。そのため、リクエストを行うたびに、常にBadRequestエラーが返されます。

だから私が得たのはこれです:

public class Asana {

    private static String apiKey;
    private DefaultHttpClient httpClient;
    private final String apiUrl = "https://app.asana.com/api/1.0/";

    public Asana(String key) {
        apiKey = key;
        httpClient = new DefaultHttpClient();
    }

    public void get(String target) {
        new APIRequest().execute(target);
    }

    private class APIRequest extends AsyncTask<String, Void, HttpResponse> {

        protected HttpResponse doInBackground(String... params) {
            String query = apiUrl + params[0];

            Log.d("#query", query);

            HttpGet get = new HttpGet(query);
            String cred = apiKey + ':';
            String encodedKey = Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);

            Log.d("#encodedKey", encodedKey);

            get.setHeader("Authorization", "Basic " + encodedKey);
            get.setHeader("Content-Type", "application/json; charset=UTF-8");

            Log.d("#getRequestLine", get.getRequestLine().toString());

            /*httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
                    new UsernamePasswordCredentials(apiKey, "")
            );*/

            HttpResponse resp = null;
            try {
                resp = httpClient.execute(get);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }

            return resp;
        }

        protected void onPostExecute(HttpResponse response) {
            StatusLine statusLine = response.getStatusLine();
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            Log.d("#statusLine", statusLine.toString());

            try {
                response.getEntity().writeTo(out);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d("#out", out.toString());
        }
    }

}

cURLまたはSimpleRESTクライアント(Chrome)を使用すると、正しい結果を返すことができます。

上記のコードで何か問題がありますか?

4

1 に答える 1

5

わかりましたので、私は自分で問題を解決しました。問題は認証にあったと思います。

Authorization ヘッダーを手動で設定する代わりに、これを使用しています。

get.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(apiKey, ""), "US-ASCII", false));

現在は正常に動作しており、正しい結果を得ることができます。

興味のある方は、github に Asana APIの Javaライブラリがあります。

于 2013-01-02T13:15:03.840 に答える