I want to use the MailChimp api to add a subscriber. As a start, want to read from one of the REST I'm trying to get a response back from the MailChimp api.
I seem to be doing the authorization correctly as I'm getting status 200, but for some reason, I am not getting the response.
Here is the code so far:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
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 is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
Looking at the MailChimp playground, it seems like I'm missing out on a lot...
How do I get the response?
****/ EDIT /****
If anyone's looking at the above code, the output should be:
System.out.println("DoPost response: \n" + sb); // not line
OK, the above code works. Basic error.
I was examining the line variable when it was null, not the response...
When I change to:
System.out.println("DoPost response: \n" + line); // not line
System.out.println("DoPost response: \n" + sb); // but sb StringBuilder
...it works.
Related
I'm sending an html request that will be used to send an email.
I would like to send an exe file in the json that will be attached to the email as well.
is it possible to do that?
URL url = new URL (url);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String jsonInputString = "{\r\n" +
" \"emailaddress\":\"user#mail.com\",\r\n" +
" \"emailSubject\": \"hello\",\r\n" +
" \"emailBody\": \"Hello from Microsoft Flow triggered by java\"\r\n" +
"}";
System.out.println(jsonInputString);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
this html request serves as a trigger for a flow in power automate
I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and I have added auth and date/time header but still I am getting unauthorised error 401. Can anyone guide me what am I doing wrong I have read the doc and added all the mandatory headers.
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
Error:
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes
I want to integrate MailChimp API in my java project. When I call Rest call using HttpURLConnection class, it responds with 401 code.
Here is my code:
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();
I will suggest using Apache Commons Codec package for encoding.
It support various formats such as Base64 and Hexadecimal.
Earlier I was also facing the same issue. I am sharing the code that I used in my application for authenticating to 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();
Now you can use StringBuilder Object sb to parse the output as required
Hope it resolves your issue :)
HTTP 401 response code means "not authorized".
You didn't set or pass your credentials properly. Is the certificate from the client set up? Here's an example of an HTTPS client.
HTTP 401 simply means you're not Authorized to send this request.
you can set username any string (the MailChimp docs suggest using anystring as a username) and your API key as a password.
In case of Postman request, you can set under the Authorization tab choose Basic Auth to set username and password. Below image shows the same.
More info about Adding/ Getting Members to/ from a Mailing List on MailChimp API 3.0, I find this article very useful.
So I want to send a GET request with parameters. But it only seems to have conventions for the url you send the request to. Unlike the POST request, I see no way to pass parameters in it.
How I send the GET request now, without parameters (might be wrong):
String url = "http://api.netatmo.net/api/getuser";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
Log.v(TAG, ("\nSending 'GET' request to URL : " + url));
Log.v(TAG, ("Response Code : " + responseCode));
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Log.v(TAG, (response.toString()));
How I send the POST request with parameters:
String url = "https://api.netatmo.net/oauth2/token";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "grant_type=password&client_id=myid&client_secret=mysecret&username=myusername&password=mypass";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.v(TAG, "\nSending 'POST' request to URL : " + url);
Log.v(TAG, "Post parameters : " + urlParameters);
Log.v(TAG, "Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Log.v(TAG, response.toString());
access_token = response.substring(17, 74);
refresh_token = response.substring(93,150);
getRequest = "/api/getuser?access_token=" + access_token + " HTTP/1.1";
Log.v(TAG, access_token);
Log.v(TAG, refresh_token);
Log.v(TAG, getRequest);
As per the HTTP specification GET supports only path params or url params and hence you cannot put the params in HTTP request body as you do in POST request.
As Sotirios mentioned in the comments, technically you can still push params in the GET body, but if the APIs are respecting the specs, they will not provide you a way to do it.
Have you tried to add the query params to the request java.net.URL?
String url = "http://api.netatmo.net/api/getuser?access_token=" + access_token;
URL obj = new URL(url);
I was encountering the same problem, trying this:
String bla = "http://api.netatmo.net/api/devicelist?access_token=" + AUTH_TOKEN;
URL url = new URL(bla);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String message = "";
while ((line = reader.readLine()) != null)
{
message += line;
}
I got an exception that the syntax was not correct. When I changed the syntax (by for example encoding with UTF 8) the API would just return errors (like 404 not found...).
I finally got it working using this:
try
{
System.out.println("Access Token: " + AUTH_TOKEN);
String url = "http://api.netatmo.net/api/devicelist";
String query = "access_token=" + URLEncoder.encode(AUTH_TOKEN, CHARSET);
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", CHARSET);
InputStream response = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
String line = "";
String message = "";
while ((line = reader.readLine()) != null)
{
message += line;
}
return message;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Note: CHARSET = "UTF-8"
Turns out the url the API provided confused me greatly. I fixed the url and it works now.
I tried the code below:
public class URLUploader {
public static void main(String[] args) throws IOException
{
URL url = new URL("http://77.203.65.164:6011");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
String name = "user";
String password = "password";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}
}
But I got the following error:
auth string: optiweb:optiweb
Base64 encoded auth string: b3B0aXdlYjpvcHRpd2Vi
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: 77.203.65.164:6011
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
at URLUploader.main(URLUploader.java:32)
What could be wrong?
First, HTTP Response Code 500 is "Internal Server Error" and has nothing to do with authentication.
Second, the statement
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
just writes the file's full pathname to the server, not the actual file contents, without even a trailing newline. This is certainly not what the server is expecting, and may be the cause of the 500 response. The request you are building and sending may have other problems as well, but without a detailed API reference for whatever's on the other end of the connection, it will be hard to provide further help.