How to make REST API call using a token? - java

I am newbie developer in Java. STEP 1 I have already done the the following:
Logged in to REST API server (with login&password)
Received a token in XML format which i parsed with SAX parser so now i
am in a position of a token. Below is the sample code for Login:
Java code:
String url1 = "https://api4.liverail.com/login";
URL obj = new URL(url1);
HttpsURLConnection con1 = (HttpsURLConnection) obj.openConnection();
String urlParameters ="username=paania#gmail.com&password=d372a15b714bd250e";
con1.setDoOutput(true);
con1.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(con1.getOutputStream());
wr.writeBytes(urlParameters);
STEP 2: I want to pass the token to REST API to obtain some information e.g a list from category but when i send the request via GET method , i get a response in XML saying [CDATA[You need to be logged in]] This is the code in Java:
String url = "http://api4.liverail.com/advertising/category/list/?token="72938howdwoi";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(newInputStreamReader(con.getInputStream()));
in.close();
con.disconnect();
I am not sure what i am missing here.
Any suggestions?

Just changed your url for request of data :
String url = "http://api4.liverail.com/advertising/category/list/?token=72938howdwoi";

Related

JSON in java by POST getting None return

I request POST by this code
URL url = new URL("adress/discordnotifi");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
JSONObject object = new JSONObject();
myPWord = ((EditText) (findViewById(R.id.edit_Id))).getText().toString();
object.put("token", tokens);
object.put("discordid", mydiscord);
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(object.toString().getBytes("UTF-8"));
Log.d("debug",object.toString());
outputStream.flush();
outputStream.close();
and my tokens and mydiscord is the information that I want to send as JSON format like
{"token":"tokens","discordid":"mydiscord"}
and from python flask
#app.route('/discordnotifi', methods=['POST'])
def post():
content = request.json
print(content)
Discordid = int(content["discordid"])
token = content['token']
"""Discordid = request.form.get("discordid")
token = request.form.get("token")"""
print(Discordid, token)
return ("Thx")
at print(content) I get None I really don't know whts wrong here. I was planning to send Json with information but I getting None from Json.
The very least you're missing is enabling output on the connection. Add:
httpURLConnection.setDoOutput(true);
The server may also require that you set some headers, for example content-type to tell it that you are sending JSON.
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
If you can use Java 11, consider using the new HttpClient class instead of HttpUrlConnection. It simplifies creating correct requests.

400 Error Paypal Token API with Java (HttpURLConnection)

I am trying to integrate Paypal using Jave(using HttpURLConnection)
API for getting token in Paypal
JDK version-1.8
Requirements:
Basic Auth Authentication -username and password.
Copied the value from Postman and added as Authentication in Header.
Body - grant_type=client_credentials as application/x-www-form-urlencoded
Adding my code:
String url = "https://api.sandbox.paypal.com/v1/oauth2/token";
HttpURLConnection con = null;
BufferedReader in = null;
String response = "";
String urlParameters="";
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("POST");
urlParameters = "grant_type=client_credentials";
//add request header
con.setRequestProperty("authorization", "Basic Value");
con.setRequestProperty("content-type","application/x-www-form-urlencoded");
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
// For POST only - START
OutputStream os = con.getOutputStream();
os.flush();
os.close();
I am getting a 400 error for all API requests.
Please help.
Is this the correct way to add the body part.

Need help on downloading a text file from a site using HttpsUrlConnection java class

I want to read the content of a text file which is located in the site
https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt
I want to read it using Java . I started it with using HttpsUrlConnection Class .
When we take the above URL in the browser , we will first redirect to a agreement page and if we click the agree button , we can see the text file . How we can do the same procedure using HttpsUrlConnection class ?
This is what I tried:
URL url = new URL("https://www.frbservices.org/EPaymentsDirectory/submitAgreement?agreementValue=Agree");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setRequestMethod("POST");
https.connect();
url = new URL("https://www.frbservices.org/EPaymentsDirectory/FedACHdir.txt");
HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.connect();
String line = "";
BufferedReader in = new BufferedReader( new InputStreamReader(http.getInputStream()));
while( (line = in.readLine()) != null )
{System.out.println(line);
//process line
logger.debug(line);
processLine(line);
}
http.disconnect();
Any inputs will be highly appreciable
Looks like the POST request to accept the agreement results in a session cookie from the server which likely stores whether or not the agreement is accepted. You could try getting the JSESSIONID cookie from the "Set-Cookie" header and sending it in your "Cookie" header to simulate the behaviour of the browser.

HttpUrlConnection addRequestProperty Method Not Passing Parameters

I have some working java code which does the following:
URL myUrl = new URL("http://localhost:8080/webservice?user=" + username + "&password=" + password + "&request=x");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// code continues to read the response stream
However, I noticed that my webserver access log contained the plaintext password for all of the users who connected. I would like to get this out of the access log, but the webserver admins claim that this needs to be changed in my code and not via webserver config.
I tried changing the code to the following:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// start of new code
myConnection.setDoOutput(true);
myConnection.addRequestProperty("username", username);
myConnection.addRequestProperty("password", password);
myConnection.addRequestProperty("request", "x");
// code continues to read the response stream
Now the access log does not contain the username/password/request method. However, the webservice now throws an exception indicating that it didn't receive any username/password.
What did I do wrong in my client code? I also tried using "setRequestProperty" instead of "addRequestProperty" and it had the same broken behavior.
I actually found the answer in another question on stackoverflow.
The correct code should be:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(myConnection.getOutputStream ());
wr.writeBytes("username=" + username + "&password="+password + "&request=x");
// code continues to read the response stream

Picasa getAlbum request not working Android

String album = "http://picasaweb.google.com/data/feed/api/user/"+email;
HttpURLConnection con = (HttpURLConnection) new URL(albumUrl).openConnection();
// request method, timeout and headers
con.setRequestMethod("GET") ;
con.setReadTimeout(15000);
con.setRequestProperty("Authorization", "GoogleLogin auth="+auth);
con.setRequestProperty("GData-Version", "2");
// set timeout and that we will process output
con.setReadTimeout(15000);
con.setDoOutput(true);
// connnect to url
con.connect();
// read output returned for url
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Problem : Everytime i call con.getInputStream() it gives me file not found exception.
But when i load the same url in the desktop browser then it is displaying correct data.
I am confused why on android it is throwing exception.
Thanks in advance.
Did you get this? Maybe you just missed the https
below example uses default for authenticated user and the experimental fields list.
url = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&access=public&fields="
+ URLEncoder
.encode("entry(title,id,gphoto:numphotosremaining,gphoto:numphotos,media:group/media:thumbnail)",
"UTF-8");
https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums

Categories

Resources