How to decode JSON from Java REST API request? - java

I'm sending data to an API from Java using POST.
What I'm trying to do is send a particular variable to the API in the POST request, and then use the value of it. But currently the value is empty. The API is definitely being called.
My Java looks like this:
String line;
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL("https://www.x.com/api.php");
String payload = "{\"variable1\":\"value1\",\"variable2\":\"value2\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
This is based on: How to send Request payload to REST API in java?
Currently the value isn't being read correctly. Am I sending it correctly in Java? Do I have to do something to decode it?

The $_POST variable is not set for all HTTP POST requests, but only for specific types, e.g application/x-www-form-urlencoded.
Since you are posting a request containing JSON entity (application/json), you need to access it as follows.
$json = file_get_contents('php://input');
$entity= json_decode($json, TRUE);

You can try to use the following code instead of your String variable payload:
List<NameValuePair> payload = new ArrayList<NameValuePair>();
payload.add(new BasicNameValuePair("variable1", "value1");
That worked for me

Related

Spring Boot : POST request returns 401 HttpUrlConnection

I'm using HttpURLConnection to send a POST request to get the access token. However, I get the error says
java.io.IOException: Server returned HTTP response code: 401 for URL: https://xyz.auth0.com/oauth/token
Note: I'm able to get the access token via Postman.
Can someone please help me? Thanks in advance!
public String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://xyz.auth0.com/oauth/token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod(TokenConstant.METHOD_POST);
//set the request content-type header parameter
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com}";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
Sample curl facebook oauth access token generation (GET request) - To generate an app access token:
curl -X GET "https://graph.facebook.com/oauth/access_token
?client_id={your-app-id}
&client_secret={your-app-secret}
&grant_type=client_credentials"
Commented few headers - Not required. Changed request to GET.
NOTE: if it works fine with curl, then your code might work fine, with few modifications.
public static String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://graph.facebook.com/oauth/access_token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod("GET");
//set the request content-type header parameter
// Commented - not required
/*connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");*/
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "client_id=<your-app-id>&client_secret=<your-app-secret>&grant_type=client_credentials";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}

JSON POST Data via HttpURLConnection

I am trying to make a request to my RESTful API using Android and HttpURLConnection. The data must be sent in the JSON format via POST data.
Here is my code:
JSONObject check_request = new JSONObject();
check_request.put("username", username);
JSONObject request = BuildRequest(check_request, "username_check", false);
Log.i("DEBUG", request.toString());
// DEBUG OUTPUT: {"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}
URL request_url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection)request_url.openConnection();
connection.setRequestProperty("User-Agent", "TheGameApp");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream os = connection.getOutputStream();
os.write(request.toString().getBytes("UTF-8"));
os.flush();
InputStream in = new BufferedInputStream(connection.getInputStream());
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
String str;
while ((str = br.readLine()) != null)
{
result += str;
}
Log.i("DEBUG", result);
//JSONObject result_json = new JSONObject(result);
os.close();
in.close();
connection.disconnect();
You can see the Debug output as a Comment. The Problem is that the API does not receive any POST data. I have used PHPs var_dump to dump $_POST and $_REQUEST which both are empty arrays.
What am I missing here?
As the question popped up if the API work. This cURL command works fine with the correct result (it is the same JSON data as the debugger printed):
curl -d '{"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}' -H "Content-Type: application/json" -X POST http://localhost/v1/api.php
Just for the sake of completeness: The example above is working. The solution to the problem was pa part in PHP on the server side, where I checked the content type and used strpos to search for application/json in $_SERVER['CONTENT-TYPE'] and switched the needle and haystack (thus searching for application/json; charset=UTF8 in the string application/json instead of the other way around).

Paypal update invoice rest api HTTP response code: 500

i am currently trying to use REST api provided by Paypal to create my own service using servlet. I manage to transfer the cURL code into HttpsURLConnection using java.
Here is my code:
JSONObject returnJson = new JSONObject();
PrintWriter out = response.getWriter();
JSONParser jparser = new JSONParser();
try{
String inputStr = request.getParameter("input");
System.out.println(inputStr);
JSONObject inputJson = (JSONObject) jparser.parse(inputStr);
String accessToken = (String) inputJson.get("access_token");
String invoiceId = (String) inputJson.get("invoiceId");
String url = "https://api.sandbox.paypal.com/v1/invoicing/invoices/"+invoiceId;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("PUT");
con.setRequestProperty("Accept-Language", "text/html; charset=UTF-8");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer "+accessToken);
//Tentatively, the input is hard coded, after integration, the input comes from http request.
//However, only merchant email in mandatory for invoice creation in sand box so far
//For details of invoice attributes please refer to this link--> https://developer.paypal.com/docs/api/#update-an-invoice
String urlJsonString = "{\"id\":\""+invoiceId+"\",\"status\":\"DRAFT\",\"merchant_info\":{\"email\":\"rui.song.2013-facilitator#sis.smu.edu.sg\",\"first_name\":\"Dennis\",\"last_name\":\"Doctor\",\"business_name\":\"MedicalProfessionals,LLC\",\"phone\":{\"country_code\":\"US\",\"national_number\":\"5032141716\"},\"address\":{\"line1\":\"1234MainSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97217\",\"country_code\":\"US\"}},\"billing_info\":[{\"email\":\"sally-patient#example.com\"}],\"shipping_info\":{\"first_name\":\"Sally\",\"last_name\":\"Patient\",\"business_name\":\"Notapplicable\",\"address\":{\"line1\":\"1234BroadSt.\",\"city\":\"Portland\",\"state\":\"LALA\",\"postal_code\":\"97216\",\"country_code\":\"US\"}},\"items\":[{\"name\":\"Sutures\",\"quantity\":100,\"unit_price\":{\"currency\":\"USD\",\"value\":\"250\"}}],\"invoice_date\":\"2014-01-07PST\",\"payment_term\":{\"term_type\":\"NO_DUE_DATE\"},\"tax_calculated_after_discount\":false,\"tax_inclusive\":false,\"note\":\"MedicalInvoice16Jul,2013PST\",\"total_amount\":{\"currency\":\"USD\",\"value\":\"250\"}}";
System.out.println(urlJsonString);
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlJsonString);
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
out.print(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer res= new StringBuffer();
while ((inputLine = in.readLine()) != null) {
res.append(inputLine);
}
in.close();
returnJson = (JSONObject) jparser.parse(res.toString());
System.out.println(returnJson);
}catch(Exception e){
e.printStackTrace();
returnJson.put("message", e);
}
out.print(returnJson);
I am testing the service on localhost, and i will manually pass in TWO parameters: "access_token" and "invoiceId" like this:
http://localhost:8080/Authentication/PaypalUpdateInvoiceServlet?input={"access_token":"A015Rv3XNo4fmFh4JC2sJiGjl1oEQ5w-B9azU.H6nlzMm1s","invoiceId":"INV2-9TRP-2S2R-OPBD-XK9T"}
These two pieces of info are obtained by me using the similar code i mentioned above.
I only modified codes in the entier HttpsURLConnection part to correspond with the cURL request and response sample provided in Paypal site. Link -->(https://developer.paypal.com/docs/api/#update-an-invoice)
Thus far, i successfully implement Create, Retrieve for invoice. I use the same way to make the servlet call with the specific parameters required and are able to get the expected response show on Paypal site.
BUT Now i am stuck with update invoice. When i make the servlet call.
i will receive:
500{"message":java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.sandbox.paypal.com/v1/invoicing/invoices/IINV2-9TRP-2S2R-OPBD-XK9T}
Can anyone help me explain why i get this error and how shall i fix this?

Java HTTP POST request (JSON) to PHP server

I have an application (Java) that needs to send json to a php web service.
This is my method to send User in JSON :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
And my php code :
$string=$_POST['json'];
I tried to insert in my database but $_POST['json'] does not exist.
I didn't see you to posting anything. Add this to your code:
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
This is not right:
con.setRequestProperty("json", json);
setRequestProperty is not used to set the HTTP payload. It is used to set the HTTP headers. For example, you should set the content type accordingly anyway. Like this:
con.setContentType("application/json");
The actual data that you are going to post goes into the HTTP body. You just write it to the end of the stream (before flush):
Here it depends on your implementation on the web server if the data needs to be escaped. If you read the body of the post and interpret it as JSON straight away, it does not need to be escaped:
wr.write(json);
If you transmit one or more JSON strings through parameters (which it looks like, since you are parsing it on the server like $_POST['json']), then you need to url-escape the string:
wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
Im not very familiar with php. You might need to url-decode the string on the server before processing the received json-string any further.
Thx for your help.
This works :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
OutputStream os = con.getOutputStream();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.write(new String("json=" + json).getBytes());
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
PHP :
$string=$_POST['json'];

Manually hitting a SOAP Service in Java, getting IO.FileNotFound exception

I need to access a .Net SOAP Service manually. All the importers have issues with its WSDL, so I'm just manually creating the XML message, using HttpURLConnection to connect, and then parsing the results. I've wrapped the Http/SOAP call into a function that is supposed to return the results as a string. Here's what I have:
//passed in values: urlAddress, soapAction, soapDocument
URL u = new URL(urlAddress);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","[star]/[star]");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String xmldata = XmlUtils.GetDocumentXml(soapDocument);
wout.write(xmldata);
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseString = "";
String outputString = "";
//Write the SOAP message response to a String.
while ((responseString = rd.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;
My problem is on the line BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); I get a "java.io.FileNotFoundException" with the address that I'm using (i.e. urlAddress). If I paste that address into a browser, it pulls up the Soap Service webpage just fine (address is http://protectpaytest.propay.com/API/SPS.svc). From what I've read, the FileNotFoundException is if the HttpURLConnection returns a 400+ error message. I added the line getResponseCode() just to see what the exact code was, and it's 404. I added the User-Agent and Accept headers from some other pages saying they were needed, but I'm still getting 404.
Are there other headers I'm missing? What else do I need to do to get this call to work (since it works in a browser)?
-shnar

Categories