0
votes

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:

1
What is the type of urlParameters?greenapps
Be sure what it means before you continue. Look it up.greenapps
I am not too sure. I looked at some of the examples stackoverflow and have being trying different things. But if you look at the curl command I don't specify any types. I think it is a default type.Mahendra Gunawardena
You should be sure about the meaning of 403 first was what i said. Look it up.greenapps
Its hard code. Using Okhttp or volley make our life more easyVlad

1 Answers

1
votes

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());
    }

}