Send an Bonanza API GET request using JAVA - java

I am trying to send a simple GET request to Bonanza API.
They give a PHP example, but i can't seem to make it work with JAVA.
This is the code page
http://api.bonanza.com/docs/reference/get_booth
I need to get the "stavgallery" booth
That is the PHP example from Bonanza
http://api.bonanza.com/docs/examples/php#get_booth
$dev_name = "xxx";
$api_url = "http://api.bonanza.com/api_requests/standard_request";
$headers = array("X-BONANZLE-API-DEV-NAME: " . $dev_name);
$args = array("userId" => "rooms_delivered");
$post_fields = "getBoothRequest=" . json_encode($args, JSON_HEX_AMP);
echo "Request: $post_fields \n";
$connection = curl_init($api_url);
$curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1); # data will be returned as a string
curl_setopt_array($connection, $curl_options);
$json_response = curl_exec($connection);
if (curl_errno($connection) > 0) {
echo curl_error($connection) . "\n";
exit(2);
}
curl_close($connection);
$response = json_decode($json_response,true);
echo "Response: \n";
print_r($response);
This is what i have so far (using Eclipse IDE):
String devId = "HIDDEN";
JSONArray stArray = new JSONArray ();
JSONObject jsonObj = new JSONObject("{'userId':'stavgallery'}");
stArray.put(jsonObj);
JSONObject jsonObjFull = new JSONObject("{'getBoothRequest':"+stArray+"}");
System.out.println(jsonObjFull.toString());
int inputLine;
URL url = new URL("http://api.bonanza.com/api_requests/standard_request");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(jsonObjFull.toString());
writer.flush();
writer.close();
inputLine = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONObject sampleReturn = new JSONObject(in.readLine());
System.out.println(sampleReturn);
getting error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: http://api.bonanza.com/api_requests/standard_request
if more info is needed please let me know
Thank you for your future help

It seems as if you don't need to put jsonObj into an array, just use jsonObj directly to construct the request:
EDIT updated with complete listing
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws JSONException, IOException {
// TODO: replace me
String devId = "XXX";
JSONObject query = new JSONObject("{'userId': 'stavgallery'}");
JSONObject jsonObj = new JSONObject("{'getBoothRequest':" + query +"}");
URL url = new URL("http://api.bonanza.com/api_requests/standard_request");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("X-BONANZLE-API-DEV-NAME", devId);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(jsonObj.toString());
writer.flush();
writer.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONObject sampleReturn = new JSONObject(in.readLine());
System.out.println(sampleReturn);
}
}

Related

Minecraft auth server returning 403?

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

java rest web service using post

I am trying to do a java rest web service using "POST" method.My client part to invoke the web service is working proper.But i am facing difficulty in accessing the passed parameters by "POST" method.Any help would be appreciable.
Here is my client side
public static void main(String[] args) throws IOException
{
String urlParameters = "param1=world&param2=abc&param3=xyz";
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}
And here is my java rest web service method to access the parameters(unable to access).
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public String getpostdata(#QueryParam("param1") String param1,#QueryParam("param2") String param2)
{
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",param1);
return jObjDevice.toJSONString();
}
When i run,I am getting
{"Hello":null} as json string instead of {"Hello":"world"}.Getting null means it is unale to access the passed parameters.Please do help.
You can use #QueryParam like shown below.
public String getpost( #QueryParam("param1") String param1,
#QueryParam("param2") String param2){
// Access both param below
}
To send data using POST request is quite straightforward.
Instead of conn.getOutputStream().write(postDataBytes); you'll have to use DataOutputStream to send data
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public static void main(String[] args) throws IOException
{
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("param1", "hello");
params.put("param2", "world");
JSONObject myJSON = new JSONObject(params);
System.out.println(myJSON);
byte[] postData = myJSON.toString().getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
//Try with Resources Example, just giving you an option
// try (DataOutputStream wr = new
// DataOutputStream(conn.getOutputStream()))
// {
// wr.write(postData);
// }
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
}
Note: You're sending application/json header in your request but I don't see a JSON in your code. It is advisable to send useful headers only
You can convert HashMap directly to JSONObject like,
org.json.JSONObject jsonObject = new org.json.JSONObject(params);
But this only works for Map<String, String>
To access the parameter in webservice, you'll have to accept JSONObject instead of accepting Map<String, String>.
public String getpost(JSONObject params) throws JSONException
{
if(params.has("param1"))
System.out.println(params.getString("param1"));
if(params.has("param2"))
System.out.println(params.getString("param2"));
//IMPLEMENT YOUR LOGIC HERE AND THEN RETURN STRING
return "your_return string";
}

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

Why my Java project can't do a succesfully POST method for connect with my OrientDB?

I have a DB and need to do a REAL POST. I did a good GET and POST is failed (I don't know where) and don't have problem in compilation.
The POST method failed:
URL url = new URL(urlPost);
HttpURLConnection conexionPost = (HttpURLConnection) url.openConnection();
conexionPost.setDoOutput(true);
conexionPost.setRequestMethod("POST");
conexionPost.setRequestProperty("Accept-Encoding", "gzip,deflate");
conexionPost.setRequestProperty("Content-Length", "216");
conexionPost.connect();
conexionPost.disconnect();
And the GET method that is ok:
String sGet = "xxxxx:2480/query/mydb/sql/...";
URL urlGet = new URL(sGet);
HttpURLConnection conexionGet = (HttpURLConnection) urlGet.openConnection();
conexionGet.setDoInput(true);
conexionGet.setRequestMethod("GET");
BufferedReader in1 = new BufferedReader(new InputStreamReader(conexionGet.getInputStream()));
String texto = "";
String request = "";
while ((texto = in1.readLine()) != null) {
request += texto;
}
in1.close();
System.out.println(request);
My code SQL for create vertex is something like this:
String urlPost = urlServer + "/command/mydb/sql/CREATE%20VERTEX%20V%20"
+ "SET%20certificateFingerprint%20=%20%27" + datos[9]+ "%27";
The answer of DB is: {"result":[]} and my DB is empty (obviously).
Thank in advance.
You are missing authentication in your POST request.
I've tried with this code and it works great:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
public class Stack38089384 {
public static void main(String[] args) throws IOException {
String urlPost = "http://localhost:2480/command/Stack38089384/sql/create%20class%20Test%20extends%20v";
URL url = new URL(urlPost);
HttpURLConnection conexionPost = (HttpURLConnection)url.openConnection();
String userCredentials = "root:root";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
conexionPost.setRequestProperty ("Authorization", basicAuth);
conexionPost.setRequestMethod("POST");
conexionPost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conexionPost.setRequestProperty("Content-Language", "en-US");
conexionPost.setUseCaches(false);
conexionPost.setDoInput(true);
conexionPost.setDoOutput(true);
System.out.println(conexionPost.getResponseCode());
}
}
Hope it helps.

I tried c2dm and i need server side

I have problem with : Google server said: 401, Unauthorized
I worked on the tomcat server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.liferay.portal.kernel.exception.SystemException;
import fr.intuitiv.dal.model.SmartPhone;
import fr.intuitiv.dal.service.SmartPhoneLocalServiceUtil;
public class URLCaller {
public static void callGoogle() throws IOException, SystemException {
URL url = new URL("https://android.clients.google.com/c2dm/send");
StringBuilder builder = new StringBuilder();
byte[] postData = null;
HttpsURLConnection conn = null;
String authorized_Key = getAuthorization();
// For each smartPhone
for(SmartPhone smartPhone : SmartPhoneLocalServiceUtil.getSmartPhones(0, SmartPhoneLocalServiceUtil.getSmartPhonesCount())) {
//Setup data
builder.append("registration_id=" + smartPhone.getRegistrationId());
builder.append("&collapse_key=").append("0");
builder.append("&data.payload=").append("The test work, drink a beer");
postData = builder.toString().getBytes("UTF-8");
//Calling server
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content_Lenght", Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authorized_Key);
// Issue the HTTP POST request
System.out.println("" + conn.getOutputStream());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.flush();
System.out.println("Google server said: " + conn.getResponseCode() + ", " + conn.getResponseMessage());
out.close();
}
}
public static String getAuthorization() throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(user.config.EMAIL);
builder.append("&Passwd=").append(user.config.PASSWORD);
builder.append("&accountType=GOOGLE");
builder.append("&source=Google-C2DM-Example");
builder.append("&service=ac2dm");// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = conn.getOutputStream();
output.write(data);
output.flush();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
output.close();
return clientAuthToken;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
I get getAuthorization() i have a huge key.
I have my regId from the phone, i send it to the server when i get new one.
I have Android Market and i am log in.
I have registration to the google c2dm.
Are you sure, that this
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
gives you the part after "Auth="?
Also you should trim the authToken because there might be a \n at the end that messes up the header:
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + StringUtils.trim(authorized_Key));

Categories