Question:
I am having trouble accessing cloud data from an Android device. I am using the POST method and expecting a JSON response. I believe I am getting 403 (forbidden) error. But I can access the same data using curl. So I believe I am doing something wrong thus seeking someones assistance.
Background
Here is the curl command string that I am trying to replicate. I receive a valid response to this command.
curl -X POST --data "token={String}¶m1={int}¶m2={int}" https://www.example.com/api/dir1/dir2"
Below is the android code.
String post_url = "https://www.example.com/api/dir1/dir2";
Thread thread = new Thread(new Runnable() {
public void run() {
try {
String urlParameters = "token={Key-string}¶m1={int}¶m2={int}";
byte[] postData = urlParameters.getBytes();
int postDataLength = postData.length;
URL url = new URL(post_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length",Integer.toString(postDataLength));
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
os.write(urlParameters.toString().getBytes("UTF-8"));
os.close();
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader( new InputStreamReader(stream ));
String data = null;
StringBuffer response = new StringBuffer();
while ((data = in.readLine()) != null) {
response.append(data);}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
References:
- POST request send json data java HttpUrlConnection
- Sending a JSON HTTP POST request from Android
- Java - sending HTTP parameters via POST method easily
- application/x-www-form-urlencoded or multipart/form-data?
- How to add parameters to HttpURLConnection using POST
- JSON Parsing, Creating a URLConnection - Android Studio