0

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}&param1={int}&param2={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}&param1={int}&param2={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:

Community
  • 1
  • 1
Mahendra Gunawardena
  • 1,864
  • 5
  • 23
  • 42

1 Answers1

1

You can try make your call in Postman (google chrome plugin), and then click in Code link. Postman will generate to you a request in many types of languages, like PHP, java, C, etc.

For example:

Add to your gradle:

compile 'com.squareup.okhttp3:okhttp:3.5.0'

Make call in somewhere:

    new Thread() {
       public void run() {
           makeCall();
       }
    }.start();

Create that class:

    public void makeCall() {

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n   \"param1\":\"data1\"}");
    Request request = new Request.Builder()
            .url("https://your_url_here")
            .post(body)
            .addHeader("content-type", "application/json")
            .addHeader("cache-control", "no-cache")
            .build();

    try {
        Response response = client.newCall(request).execute();

        Log.e("okmsg1", response.toString());
        Log.e("okmsg2", response.message());
        Log.e("okmsg3", response.body().string());

    } catch (IOException e) {
        Log.e("err", e.getMessage());
    }

}