0

UNIX で実行するために使用する Curl コマンドがあります。

curl --digest -u 'user':'pass' 'https://<URL>/getCustomers' (which is working for me)

私はJavaを使ってこれをやろうとしていました。

Restlet と HttpClient を使用してみましたが、どれも機能しません。それを実装する正確な方法はわかりません。

private static void get() {
try {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpGet getRequest = new HttpGet("https://<URL>/getCustomers");

    getRequest.addHeader("accept", "application/json");
    HttpResponse response = httpClient.execute(getRequest);

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER, PASSWORD));

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;

    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

  } catch (ClientProtocolException e) {

    e.printStackTrace();

  } catch (IOException e) {

    e.printStackTrace();
  }
}

どこで間違えたのかわからないのですが、助けていただけますか?出力は JSON ですが、出力をキャッチする方法も教えてもらえますか?

4

1 に答える 1

0

あなたの質問は、あなたが得るエラーが何であるかなどのいくつかの詳細を見逃しています。

HTTPClientのドキュメント、より具体的には認証とプリエンプティブの仕組みに関するセクションを読むことをお勧めします。

次に、ステータスコードとエンティティを直接処理する代わりに、次のように流暢なAPIを切り替えることができます。

Executor executor = Executor.newInstance()
        .auth(new HttpHost("example.com"), "username", "password")
        .authPreemptive(new HttpHost("example.com"));

executor.execute(Request.Get("http://example.com/foobar.json"))
        .returnContent().asString();
于 2013-01-10T16:38:01.750 に答える