0

Java プロジェクトに MailChimp API を統合したいと考えています。HttpURLConnection クラスを使用して Rest 呼び出しを呼び出すと、401 コードで応答します。

これが私のコードです:

URL url = new URL("https://us13.api.mailchimp.com/3.0/lists");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "apikey <my-key>");

String input = "<json data>";

OutputStream os = conn.getOutputStream();
//os.write(input.getBytes());
os.flush();

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
    throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}

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

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

conn.disconnect();
4

3 に答える 3

4

エンコードにはApache Commons Codecパッケージを使用することをお勧めします。Base64 や 16 進数など、さまざまな形式をサポートしています。

以前、私も同じ問題に直面していました。Mailchimp API v-3.0 への認証のためにアプリケーションで使用したコードを共有しています。

//basic imports
import org.apache.commons.codec.binary.Base64;
.
.
.
 //URL to access and Mailchimp API key 
String url = "https://us9.api.mailchimp.com/3.0/lists/";
//mailchimp API key 
String apikey = xxxxxxxxxxxxxxxxxxxxxxxxxxx

// Authentication PART

String name = "Anything over here!";
String password = apikey;     //Mailchimp API key
String authString = name + ":" + password;

byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection)           urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);

InputStream is1 = httpConnection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is1, "utf-8"));

String line = null;
while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
            }
br.close();

StringBuilder Object sbを使用して、必要に応じて出力を解析できるようになりました

問題が解決することを願っています:)

于 2016-08-09T20:42:14.593 に答える