I am using Quickblox REST APIs. When i am trying to run from POSTMAN , it is giving me proper output. but , when i am using it through my java code. It is showing me below error :
auth_key is required
Here is my java code :
URL url = new URL("https://api.quickblox.com/session.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
String current_date = dateFormat.format(cal.getTime());
Date newdt = dateFormat.parse(current_date);
long unixTime = newdt.getTime() / 1000;
String nonce = randomString(5);
String message ="application_id=XXXXX&auth_key=XXXXX&nonce=xxxxtimestamp=xxxx";
JSONObject arrayElement = new JSONObject();
arrayElement.put("application_id", "xxxxxx");
arrayElement.put("auth_key", "xxxxxxx");
arrayElement.put("nonce", nonce);
arrayElement.put("timestamp", unixTime);
arrayElement.put("signature", hmacDigest(message, secret, "HmacSHA1"));
conn.setRequestProperty("data", arrayElement.toJSONString());
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
HashMap hmdata = new HashMap();
while ((inputLine = in.readLine()) != null) {
hmdata.put("data", inputLine);
}
in.close();
Can anybody help me to resolve this error?
If you send as json then add the following header:
conn.setRequestProperty("Content-Type", "application/json");
because the server does not understand in what format you send the request's payload
Related
I've done some research on using HttpUrlConnect and most examples I've seen uses either
a) a params string which looks like this:
paramString = "param1=someParam¶m2=2ndparam¶m3=3rdparam";
b) uses a put method to place the parameters:
JSONObject json = new JSONObject();
json.put("param1", "Parameter");
json.put("param2", "Parameter2");
json.put("param3", "Parameter3");
The format I want to send looks like this:
{
"grant_type":"password",
"username":"testuser#someid.com",
"password":"testPwd123$"
}
Is there a way for me to send a formatted JSON string instead of setting parameters or using a param string? The code I'm using to send my POST request looks like the following:
public static String PostRequest(String urlString, String token, String jsonString) throws IOException {
byte[] postData = jsonString.getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty ("Authorization", "Bearer " + token);
conn.setUseCaches(false);
try( DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
int responseCode = conn.getResponseCode();
System.out.println("POST response code: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
I'm open to suggestions whether to use a different library, or if there are any code changes that I should make in order to take a JSON formatted string.
Am trying to create a JAVA GET Http connection request with JSON Array data as shown below. where as the same code works with out any parameter (i.e. ?data={..})
String myurl = "https://myserver.com/test/api/v1/parameter?data={"username":{"name":"testusername"},"salary":{"sal":"56748","bonus":"3221"},"category":{"cat":"CATA"}}";
String newmyurl = myurl.replaceAll("\"","\\\"");
log.info("**newmyurl*** "+newmyurl);
URL url = new URL(newmyurl);
log.info("**URL*** "+url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// By default it is GET request
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode(); // Code breaks here nothing errors in log
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer sb = new StringBuffer();
while ((output = in.readLine()) != null) {
sb.append(output);
}
in.close();
//printing result from response
log.info("****return string****"+sb.toString());
To escape characters in a URL, use URLEncoder:
String myjson = "{\"username\":{\"name\":\"testusername\"},\"salary\":{\"sal\":\"56748\",\"bonus\":\"3221\"},\"category\":{\"cat\":\"CATA\"}}";
String myurl = "https://myserver.com/test/api/v1/parameter?data=" + URLEncoder.encode(myjson, "UTF-8");
From my little knowledge of 500 errors I understand it is a server error. But what could be the root cause behind something like this? Could it be on my end?
The error i'm getting is:
{"status":500,"error":"An unexpected error occurred."}
Could it have to do with my headers i.e missing one? From what i've found from testing the error changes from 400 errors i.e 401 after adding the user agent header.
my code looks as follows:
String url="https://api.gotinder.com/auth";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Host", "host url");
//con.setRequestProperty("content-Length" , "287");
con.setRequestProperty("User-Agent" , "Tinder/4.0.4");
con.setRequestProperty("facebook_token", "token");
//con.setRequestProperty("facebook_id", "id");
System.out.println(con.getResponseCode());
Side note: This is all for educational purpose. I got intrigued.
The problem was I was passing my token as a Property and not a part of the body.
code:
String urlstr = "https://api.gotinder.com/auth";
String params = "facebook_token=" + this.fb_token;
URL url = new URL(urlstr);
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setDoInput(true);
urlconn.setDoOutput(true);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("User-Agent", "Tinder/3.0.4 (iPhone; iOS 7.1; Scale/2.00)");
urlconn.setRequestProperty("Content-Language", "en-US");
OutputStream os = urlconn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.close();
os.close();
if (urlconn.getResponseCode() == 200) {
BufferedReader bR = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while ((line = bR.readLine()) != null) {
responseStrBuilder.append(line);
}
urlconn.getInputStream().close();
JSONObject result = new JSONObject(responseStrBuilder.toString());
user_token = result.getString("token");
System.out.println("User token is: " + user_token);
} else {
System.out.println("Want to print error here had getting data...");
}
Hello all i am trying to capture the json "post" data from the client and send it to other client i.e i am trying to get the data of the client who hit my url and i handle this data and send it to the actual url.For this i have created an internal post client where i handle the data and send to my actual url.
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String a = book.getId();
String b = book.getName();
String c = book.getAuthor();
String d = book.getPrice();
System.out.println(a + b + c + d);
byte[] out = "{\"id\":\"root\",\"name\":\"password\",\"price\":\"root\",\"author\":\"password\"}"
.getBytes();
int length = out.length;
conn.setFixedLengthStreamingMode(length);
conn.setRequestProperty("Content-Type",
"application/json; charset=UTF-8");
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(out);
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((output = br.readLine()) != null) {
response = output;
}
// return parseJSON(response);
return response;
I want to place my values of the strings a,b,c,d with the root,password,root,password respectively.
But when i try to place it i get the error insert missing quote.
Please help me regarding this
Thank you
Moving Comment to Answer as it worked for OP.
you can convert string to byte array as below:
byte[] request = new String("{\"id\":\"" + a + "\",\"name\":\"" +b+"\",\"price\":\"" + c+" \",\"author\":\"" + d+ "\"}").getBytes()
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.