I am using Parse REST API for a game, altough there are java libraries for Parse I would like to handle the transfer protocolls my self using java.net for learning purposes. Please look away from things like, why dont I use Apache HttpClient.
Following the Parse REST API Guide
Here is what I am trying to achive:
Signup
User Login
validating session tokens / Retriving current user
The first two steps works just fine, the former using POST request method and the latter using GET with some paramaters.
Keeping the Request and Response format in mind I also provide the Application-ID and the REST-API-Key which are the appropriate request headers needed.
Now, for the third step using GET request with no paramaters, but with an additional header, the API expects there to be a Session-Token provided.
Code
private static void validateSessionToken(String token) throws IOException {
System.out.println("Token: " + token);
URL url = new URL("https://api.parse.com/1/users/me");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-Parse-Application-Id", "xxxxxxx");
con.setRequestProperty("X-Parse-REST-API-Key", "xxxxxxxx");
con.setRequestProperty("X-Parse-Session-Token", token);
con.setRequestProperty("content-type", "application/json");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
if(responseCode == 400) {
System.out.println("Bad request!");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
Outputs
Sending 'GET' request to URL : https://api.parse.com/1/users/me
Response Code : 400
Bad request!
Debugging
I have been using the PARSE API CONSOLE and Chrome network debugging tool to try and see what the difference is, but cannot see any.
From wiki:
400 Bad Request
The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing)
Some photos that may help
So when I asked my JsonObject for the session token:
jsonObject.get("sessionToken").toString();
It returned: "r:WzB7qdmhkcW5qd2moM8gbBLDp" in quotation, but using:
jsonObject.get("sessionToken").getAsString();
it returned: r:WzB7qdmhkcW5qd2moM8gbBLDp
I was so focused on the request I did not even notice...
Related
I just want to start Nifi processor through REST API java code, i am able to invoke HTTP connection and able to see play button on processors but flow is not happening? and i have multiple processes group in which my first processor is GETSplunk Template which is in cron driven ,manual start is good and fine and when i start through API flow is not working, and changed to Timer schedule it is showing error for SQL template ,can any one bumped with this issue, please suggest me.
sample API code is.
String url = "http://hostname:8080/nifi-api/flow/process-groups/{id};
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic put request
con.setDoOutput(true);
con.setRequestMethod("PUT");
con.setRequestProperty("Content-Type","application/json");
String putJsonData = "{\r\n" +
"\"component\":{\r\n" +
"\"id\":\"<processor-group id>\",\r\n " +"\"state\":\"RUNNING\"\r\n" + "}";
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(putJsonData);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("nSending 'POST' request to URL : " + url);
System.out.println("Post Data : " + putJsonData);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader( new
InputStreamReader(con.getInputStream())); String output; StringBuffer
response = new StringBuffer();
while ((output = in.readLine()) != null) { response.append(output); }
in.close();
//printing result from response
System.out.println(response.toString());
}
#Sravya99 When I need to trigger flow from outside of Nifi, I often create a NiFi API interface listening on a port via HandleHttpRequest and HandleHttpResponse. This can be very simple request, or very complicated with ssl, access and authorization, etc. It should serve fine for your purpose, leaving your flow always on, and initiating the triggered responses using the HandleHttpRequest.
I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
I want to set a successful request to Neteller, I am trying to get an access token using the code from the Neteller documentation. However, it consistently fails with with the following exception:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials
Here's the code (again, from the Neteller documentation):
String testUrl = " https://test.api.neteller.com";
String secureUrl = "https://api.neteller.com";
String url = testUrl;
if("live".equals(configBean.get("environment"))){
url = secureUrl;
}
url += "/v1/oauth2/token?grant_type=client_credentials";
String xml = "grant_type=client_credentials?grant_type=client_credentials";
xml = "";
String test = Base64.encodeBytes((accountID + ":" + secureID).getBytes());
try {
URL urls = new URL ("https://test.api.neteller.com/v1/oauth2/token?grant_type=client_credentials");
HttpURLConnection connection = (HttpURLConnection) urls.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Bearer " + test);
connection.setRequestProperty ("Content-Type", "application/json");
connection.setRequestProperty ("Cache-Control", "no-cache");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String accessToken = "";
} catch(Exception e) {
e.printStackTrace();
}
Why is my implementation failing here?
There is nothing wrong with your code. The problem is that you are trying use a regular member account for the API integration, where you need to be using a merchant account for that. Below are the steps you will need to complete in order to get it to work:
You need to get a test merchant account (http://www.neteller.com/business/contact-sales/). Registering on www.neteller.com creates a regular member account, which cannot receive payments via the API.
Once you have a test merchant account, you will need to white-list the IP address from which you will be making requests to the API. (pg. 31 of the manual).
Then, you will need to add an application to it (pg. 32 of the manual).
Once you have added the application, use the "client ID" and "client secret" in the Authorization header - just like you do now, base64 encoded values, separated with colon (:).
I have a problem with a WebService on Android. I am getting a 400 error but there is no information on the ErrorStream.
What I am trying to do is a POST request on a WCF Webservice using JSON.
I must add that I have includeExceptionDetailInFaults Enabled on my Service. The last time I got a 400 error, it was because I hadn't defined the RequestProperty. Now I don't get any error in the stream.
Here is the code:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
// In my last error I had not included these lines. Maybe they are still wrong?
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out);
outputStreamWriter.write(jsonObject.toString(), 0, jsonObject.length());
outputStreamWriter.flush();
//outputStreamWriter.close();
int code = urlConnection.getResponseCode();
System.out.println(code);
if(code == 400) {
BufferedInputStream errorStream = new BufferedInputStream(urlConnection.getErrorStream());
InputStreamReader errorStreamReader = new InputStreamReader(errorStream);
BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = bufferedReader.readLine()) != null) {
builder.append(aux);
}
String output = builder.toString(); // The output is empty.
System.out.print(output);
}
Check Retrofit library from Square it's more easy and thin for GET/POST request and especially for REST. I suggest you to try it. It will make your life easy.
You can use different JSON parsers, error handlers, etc. Very flexible.
POST request definition using retrofit it's simple like this:
An object can be specified for use as an HTTP request body with the #Body annotation.
#POST("/users/new")
void createUser(#Body User user, Callback<User> cb);
Methods can also be declared to send form-encoded and multipart data.
Form-encoded data is sent when #FormUrlEncoded is present on the method. Each key-value pair is annotated with #Field containing the name and the object providing the value.
#FormUrlEncoded
#POST("/user/edit")
User updateUser(#Field("first_name") String first, #Field("last_name") String last);
After you define method inside your Java interface like shown above instantiate it:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.soundcloud.com")
.build();
MyInterface service = restAdapter.create(MyInterface.class);
And then you can call your method synchronously or asynchronously (in case you pass Callback instance).
service.myapi(requestBody);
See Retrofit documentation (http://square.github.io/retrofit/javadoc/index.html) and samples on GitHub for more details.
A 400 error might be occuring (and usually occurs in my case) because of incorrect URL or bad JSON format in post. please check those two
Using an HttpPost object will make your job a lot easier in my opinion
HttpPost post = new HttpPost(url);
if(payload != null){
try {
StringEntity entity = new StringEntity(payload,HTTP.UTF_8);
entity.setContentType(contentType);
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
LOG.d(TAG, "post err url : " + url);
LOG.e(TAG, "post err url" , e);
throw new Exception(1, e);
}
}
HttpResponse response=executeRequest(owner, post);
I am trying to connect to a URL from a desktop app, and I get the error indicated in the Title of my question, but when I tried to connect to the same URL from servlet, all works fine. When I load the URL from browser, all works fine. I am using the same code in the servlet. The code was in a library, when it didn't work, I pulled the code out to a class in the current project, yet it didn't work.
The URL https://graph.facebook.com/me.
The Code fragment.
public static String post(String urlSpec, String data) throws Exception {
URL url = new URL(urlSpec);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
I'm a little bit confused here, is there something that is present is a servlet that is not a normal desktop app?
Thanks.
FULL STACK TRACE
Feb 8, 2011 9:54:14 AM com.trinisoftinc.jiraffe.objects.FacebookAlbum create
SEVERE: null
java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.facebook.com/me
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1313)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at com.jiraffe.helpers.Util.post(Util.java:49)
at com.trinisoftinc.jiraffe.objects.FacebookAlbum.create(FacebookAlbum.java:211)
at com.trinisoftinc.jiraffe.objects.FacebookAlbum.main(FacebookAlbum.java:261)
EDIT: You need to find the exact error message that facebook is sending in the response
You can modify your code to get the message from the error stream like so:
HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
Take a look at how you are passing the user context
Here's some information that could help you out:
Look at the error message behind the 400 response code:
"Facebook Platform" "invalid_request" "An active access token must be used to query information about the current user*
You'll find the solution here
HTTP/1.1 400 Bad Request
...
WWW-Authenticate: OAuth "Facebook Platform" "invalid_request" "An active access token must be used to query information about the current user."
...
I finally found the problem. Of course it's my code. One part of the code I didn't post is the value of data. data must contain only name and description but I am passing more than name and description.