How to make POST in android studio?

Asked

Viewed 126 times

1

I’m trying to do a POST for my local API but I’m finding some problems and I’m not getting it right what I’m doing wrong.

POST that works on Postman is with a body more or less like this:

[
    {
        "user_id": "8888888",
        "search": "-57,-63,-63,-64,-100,-100",
        "date": "2020-03-21 01:31:23"
    }
]

In Android studio I’m trying with the Httpservice class in this way:

public class HttpService extends AsyncTask<Void, Void, SendData> {

    private final String search;
    private final String date;
    private final Integer ra;

    public HttpService(String busca, Integer ra, String data){
        this.search = busca;
        this.date = data;
        this.ra = ra;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected SendData doInBackground(Void... voids) {

 if(this.search != null && this.date != null && this.ra != null){
            try {
URL url = new URL("http://192.168.0.20:5000/api/v1/resources/positions/app");

                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");

                con.setRequestProperty("Content-Type", "application/json; utf-8");
                con.setRequestProperty("Accept", "application/json");

                con.setDoOutput(true);

//                connection.setConnectTimeout(5000);
//                connection.connect();
//                JSONObject postData = new JSONObject();
//                postData.put("user_id", this.ra);
//                postData.put("search", this.search);
//                postData.put("date", this.date);
//                Log.d("DEBUG postData", ""+postData);

                String jsonInputString = "{\"user_id\": \""+this.ra+"\", \"search\":\""+this.search+"\", \"date\":\""+this.date+"\"}";

                Log.d("DEBUG Json", "{\"user_id\": \""+this.ra+"\", \"search\":\""+this.search+"\", \"date\":\""+this.date+"\"}");
                try(OutputStream os = con.getOutputStream()){
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }

                int code = con.getResponseCode();
                System.out.println(code);

                try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
                    StringBuilder response = new StringBuilder();
                    String responseLine = null;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    Log.d("DEBUG response",""+response.toString());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

In my Mainactivity I have a switch. So basically to use it I did the following:

In onCreate it was like this:

Switch aSwitch = (Switch) findViewById(R.id.switch1);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    try {
                        showMessage();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

And the showMessage(); Has a Toast that was started and created some parameters to test:

 private void showMessage() throws ExecutionException, InterruptedException {
        hora = getCurrentTime();
        data = getCurrentDate();
        datetime = (data+" "+hora);
        datetime = datetime.substring(0,datetime.length() -3);
        Integer ra = 9988776;
        String search = "-100,-67,-63,-49,-53,-48";
        Toast.makeText(this, "Localização Ativada! "+datetime, Toast.LENGTH_SHORT).show();
        Log.d("DEBUG", "Busca: "+search+", ra: "+ra+", Data: "+datetime);
        new HttpService(search, ra, datetime).execute().get();
    }

Output from Android Studio:

There are some DEBUG.. that I use to see how are the outputs and I decided to keep to be more visible

2020-03-23 12:10:48.273 7325-7408/com.example.peterson.whereiam21 I/Adreno: QUALCOMM build                   : cf57c9c, I1cb5c4d1cc
    Build Date                       : 09/23/18
    OpenGL ES Shader Compiler Version: EV031.25.03.01
    Local Branch                     : 
    Remote Branch                    : 
    Remote Branch                    : 
    Reconstruct Branch               : 
2020-03-23 12:10:48.273 7325-7408/com.example.peterson.whereiam21 I/Adreno: Build Config                     : S L 6.0.7 AArch64
2020-03-23 12:10:48.284 7325-7408/com.example.peterson.whereiam21 I/Adreno: PFP: 0x005ff112, ME: 0x005ff066
2020-03-23 12:10:48.288 7325-7408/com.example.peterson.whereiam21 I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-03-23 12:10:48.289 7325-7408/com.example.peterson.whereiam21 I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2020-03-23 12:10:48.291 7325-7408/com.example.peterson.whereiam21 I/OpenGLRenderer: Initialized EGL, version 1.4
2020-03-23 12:10:48.291 7325-7408/com.example.peterson.whereiam21 D/OpenGLRenderer: Swap behavior 2
2020-03-23 12:10:48.445 7325-7325/com.example.peterson.whereiam21 I/AssistStructure: Flattened final assist data: 3104 bytes, containing 1 windows, 10 views
2020-03-23 12:10:51.056 7325-7325/com.example.peterson.whereiam21 D/DEBUG: Busca: -100,-67,-63,-49,-53,-48, ra: 9988776, Data: 2020-03-23 12:10
2020-03-23 12:10:51.062 7325-7457/com.example.peterson.whereiam21 I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
2020-03-23 12:10:51.068 7325-7457/com.example.peterson.whereiam21 D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-03-23 12:10:51.072 7325-7457/com.example.peterson.whereiam21 D/DEBUG Json: {"user_id": "9988776", "search":"-100,-67,-63,-49,-53,-48", "date":"2020-03-23 12:10"}
2020-03-23 12:10:51.131 7325-7457/com.example.peterson.whereiam21 I/System.out: 500
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err: java.io.FileNotFoundException: http://192.168.0.20:5000/api/v1/resources/positions/app
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at com.example.peterson.whereiam21.HttpService.doInBackground(HttpService.java:125)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at com.example.peterson.whereiam21.HttpService.doInBackground(HttpService.java:41)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:333)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-03-23 12:10:51.132 7325-7457/com.example.peterson.whereiam21 W/System.err:     at java.lang.Thread.run(Thread.java:764)

API console

My API is a python with flask and works correctly in the browser and in Postman

192.168.0.7 - - [23/Mar/2020 12:10:50] "POST /api/v1/resources/positions/app HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/peterson/.local/lib/python3.5/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/peterson/projects/tcc/api/api_main.py", line 222, in positions_post_app
    user_id = user['user_id']
TypeError: string indices must be integers

He says it needs to be integers but in json it only sends string. That’s when :/

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.