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.
Related
I'm trying to get a token from my GitHubApp using the step by step tutorial on GitHub.
Step 1 is to get the code with http GET https://{GitHubEntreprise}/login/oauth/authorize
URL url = new URL("https://{GitHubEntreprise}/login/oauth/authorize");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("client_id", "Iv1...");
ParameterStringBuilder parameterStringBuilder = new ParameterStringBuilder();
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(parameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.getResponseCode();
The response code is 403. Trying to call it by Postman and it return me a html page... i don't really understand.
The goal of this subject is to be able to read a file on a private git hub organisation
Have you got an idea ?
I have a problem on HttpURLConnection in post method. Everything is working fine on get method however, when I try to use Post method. I'm getting this error message.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL
Here's my code snippet. I hope you could help me about this.
URL url = new URL(my url/userInfo);
String encoding = Base64.getEncoder().encodeToString(("username:password").getBytes("UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("x-csrf-token", "fetch");
String csrfToken = connection.getHeaderField("x-csrf-token");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String output = in.readLine();
in.close();
String content = data // expected data to retrieve
URL url2 = new URL(my URL);//another url to push the data retrieve
HttpURLConnection connection2 = (HttpsURLConnection) url2.openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
connection2.setRequestProperty("Authorization", "Basic " + encoding);
connection2.setRequestProperty("Accept", "application/json");
connection2.setRequestProperty("x-CSRFToken", csrfToken);
connection2.setRequestProperty("cache-control", "no-cache");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(data);//this is where the data will be pushed
osw.flush();
osw.close();
os.close();
the idea is, we need first to get the x-csrf-token and data from the first link, which is okay. After GET Method execution, the POST method will occur. unfortunately, the post method is not working. I'm getting the error message shown above. By the way, we tried to do a post method in POSTMAN and it' working fine.
Hoping you could help me about this.
I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.
I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.
String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//Setting the Request Method header as POST
con.setRequestMethod("POST");
//Prepairing credentials
String cred= "user123:p#ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);
//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);
//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");
//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");
con.setDoOutput(true);
JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
OutputStream os = con.getOutputStream();
os.write(jsonObject.toJSONString().getBytes());
os.flush();
WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();
Get the input stream and read it.
String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}
I have to write the most basic POST client in Java.
It sends a few parameters to a Certificate server.
The parameters are supposed to be JSON encoded
I have the attached code, how do I make the params JSON encoded?
String url = "http://x.x.x.x/CertService/revoke.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "serialnumber=C02G8416DRJM&authtoken=abc&caauthority=def&reason=ghi";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Can you just set your content type as application/json and send the json string?
con.setRequestProperty("Content-Type", "application/json");
The text you're POSTing in your example looks like it's application/x-www-form-urlencoded. To get application/json encoding, prepare the parameters as a map, then use any of several JSON encoding libraries (e.g., Jackson) to convert it to JSON.
Map<String,String> params = new HashMap<>();
params.put("serialnumber", "C02G8416DRJM");
params.put("authtoken", "abc");
...
ObjectMapper mapper = new ObjectMapper();
OutputStream os = con.getOutputStream();
mapper.writeValue(os, params);
os.flush();
os.close();
...
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";