JSON POST Data via HttpURLConnection - java

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).

Related

Pass json object by navigator instead of java

I have a java application with this code :
URL url = new URL("http://myurl/");
HttURLConnection connection = (HttURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutplut(true);
connection.setRequestProperty("Content-Type", "application/json");
BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
buffer.write("{\"foo:\"0}");
buffer.flush();
I just want to do the samething in my navigatour URL bar.
Edit
I found a tool to modifier headers. Here a screenshoot of the dev tool when I load my page.
Now where did I put my Json object?
If you need to send JSON data to your URL your code should be like this,
URL url = new URL("http://myurl/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
String input = "{\"foo\":\"bar\"}";
OutputStream ous = con.getOutputStream();
ous.write(input.getBytes());
ous.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}else
{
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
System.out.println(output);
}
}
con.disconnect();
If you need GET Method then you can place this,
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
If you need to send Request Body with the URL you can use CURL. And also you can use POSTMAN. By using this you can send requests and receive the response.
CURL will be like this,
curl -v -H "Content-Type: application/json" -X POST \
-d '{\"foo\":\"bar\"}' http://myurl/
You can use Firefox to perform what you need, Read the 2nd answer.

Ameritrade API POST Request JSON Response

I haven't coded in JAVA for years, and am trying to put an algorithm together to automatically make trades based on certain conditions.
I'm hoping to use the Ameritrade API
I've tried sending a cURL message in command prompt and I do indeed get a response back from the server 'Invalid Key'. I'd like to see the 'Invalid Key' response come back in Java as this will prove that I can send POST and receive JSON objects back into Java. From there I will work at authenticating but one step at a time!
Here's the curl message sent in command prompt that works, try it yourself by copying and pasting::
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=authorization_code&refresh_token=&access_type=offline&code=&client_id=&redirect_uri=" " https://api.tdameritrade.com/v1/oauth2/token
The first thing I'd like to do is be able to send this curl message in JAVA and receive the JSON response back in JAVA
This is what I have for code so far, but I get a 500 error, which makes me think its something with the way im sending the message to the server?
public void trytoAuthenticate() {
HttpURLConnection connection = null;
//
//this is the curl message in command prompt you can send to receive JSON response back
//curl -X POST --header "Content-Type: application/x-www-form-urlencoded" -d
//"grant_type=authorization_code&
//refresh_token=&
//access_type=offline&
//code=&
//client_id=&
//redirect_uri=" "https://api.tdameritrade.com/v1/oauth2/token"
try {
//Create connection
URL url = new URL("https://api.tdameritrade.com/v1/oauth2/token");
String urlParameters = "grant_type=" + URLEncoder.encode("authorization_code", "UTF-8") +
"&refresh_token=" + URLEncoder.encode("", "UTF-8") +
"&access_type=" + URLEncoder.encode("", "UTF-8") +
"&code=" + URLEncoder.encode("", "UTF-8") +
"&client_id=" + URLEncoder.encode("", "UTF-8") +
"&redirect_uri=" + URLEncoder.encode("", "UTF-8");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); //-X
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //-H
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);//connection will be output
connection.setDoInput(true);//connection will be input
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(urlParameters);
System.out.println(urlParameters); //added for testing
wr.close();
//Get Response
DataInputStream is = new DataInputStream (connection.getInputStream());
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
rd.readLine();
//StringBuffer response = new StringBuffer(); // or StringBuffer/StringBuilder if Java version 5+
//String line;
//while ((line = rd.readLine()) != null) {
// response.append(line);
// response.append('\r');
//}
rd.close();
//System.out.println(response.toString());
//return response.toString();
} catch (Exception e) {
e.printStackTrace();
//return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
A few things:
You need four parameters: grant_type, access_type, redirect_url and code.
You should URLDecode the authorization code you got from the browser login you probably just performed (as per their instructions)
Remove empty parameters, leave only what I mentioned above.
The redirect URL must match EXACTLY the redirect URL you added when you created your APP in the console.
If this is an app (looks like it), you probably have to set the access_type to "offline". Again see their documentation. Depends on your application.
grant_type should be "authorization_code", as that's what you want.

Convert cURL to Java for SOAP Call

Im implementing a SOAP web service and it is working with a cURL call. I implemented following this tutorial. The service is working with the following command:
curl --header "content-type: text/xml" -d #request.xml http://localhost:8080/ws
But of course this action has to be free from command prompt and be able to be called whenever necessary, so I want to relate this service to an action when a method is called for example.
So far I found from internet
String url = "http://localhost:8080/ws";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestProperty("Content-Type", "text/xml");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
I assume it should be a POST method but how do I add the "request.xml" and "--header"? What command will finalize the cURL call? Or am I doing this totally wrong and the long way, is there an easier way?
PS: I already have a web service running and Im using Eclipse Oxygen.
Add below lines to your code at the end, it will do the JOB.
OutputStream wr = new DataOutputStream(conn.getOutputStream());
BufferedReader br = new BufferedReader(new FileReader(new File("request.xml")));
//reading file and writing to URL
System.out.println("Request:-");
String st;
while ((st = br.readLine()) != null) {
System.out.print(st);
wr.write(st.getBytes());
}
//Flush&close the writing to URL.
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.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:-" + response.toString());
While HttpURLConnection can be used for this purpose, SOAPConnection was designed for situations where there is not a WSDL.
The code below is much simpler:
SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage msg =
MessageFactory.newInstance()
.createMessage(null, Files.newInputStream(Paths.get("request.xml")));
SOAPMessage resp = conn.call(msg, "http://localhost:8080/ws");
resp.writeTo(System.out);

POST data sent from android app not being received by PHP file

I am trying to send data (a student id#) from an Android app to a PHP file via the body of an HTTP POST request. Then the PHP file will send data (just a string for now) back to the app. However, my php doesn't seem to be able to read my POST data (student id#) from the request.
My .java file:
JSONObject jsonParam = new JSONObject();
DataOutputStream printout;
String idIN = params[0];
jsonParam.put("id_in", idIN);
BufferedReader input;
String result;
URL url = null;
HttpURLConnection urlConnection = null;
url = new URL("http://10.0.2.2/project/connector.php");
urlConnection = (HttpURLConnection) url.openConnection();
//prepare request
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
printout = new DataOutputStream(urlConnection.getOutputStream ());
//printout.write(jsonParam);
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
//this returns: {"id_in":"1010101"}
Log.d("json out: ", jsonParam.toString());
printout.flush();
printout.close();
int response = -1;
response = urlConnection.getResponseCode();
input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
result = input.readLine();
// This returns 200
Log.d("response code: ", result);
urlConnection.disconnect();
MY .PHP FILE:
<?php
header('Content-Type: text/html; charset=utf-8');
$id_in = "";
echo "test1";
$id_in = trim($_POST['id_in']);
echo "test2";
if (isset($_POST['id_in'])) {
echo "good";
}else{
echo "bad";
}
mysqli_close($myconn);
My Android app is receiving a 200 response code and is receiving "test1" in the response, but not "test2", so the problem must be occuring when my PHP file tries to read the POST data: $id_in = trim($_POST['id_in']);
don't forget to use urlConnection.connect();

How to decode JSON from Java REST API request?

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

Categories