Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method does not support request body:GET

Tags:

java

android

 class MySync extends AsyncTask{ ProgressDialog mProgressDialog;

    protected void onPreExecute(){
       mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
    }
    @Override
    protected Integer doInBackground(String... params)  {
        int result = 0;
       //String url="http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]";
        int code;
        try {
            URL hp=new URL("http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]);
            HttpURLConnection urlConnection=(HttpURLConnection)hp.openConnection();
            urlConnection.connect();
            Log.i("A", "connect");
            code=urlConnection.getResponseCode();
            Log.i("A","code");
            boolean a=check(code);

           if(a){
                //urlConnection.setDoInput(true);
                Log.i("A", "input");
               // urlConnection.setDoOutput(true);
                Log.i("A", "output");
                urlConnection.setRequestMethod("GET");
                Log.i("A", "get");
                byte [] buf=("key1=" + params[0] + "&key2=" + params[1]).getBytes();
                urlConnection.getOutputStream().write(buf);
                Log.i("A", "sent");
            }
            else{
                Log.i("A","error");
                result=3;
            }
        }
        catch (MalformedURLException e) {
            Log.i("e", "Error");
        }
        catch (IOException e){
            e.printStackTrace();
        }
    protected boolean check(int c){
            if(c==200) return true;
            else return false;
        }
   }

This code gives error method does not support a request body:get? also if i insert setdooutput(true) then it gives error already connected. I am newbie to android and i am making my college project

like image 764
Mayank Singh Avatar asked Sep 26 '22 04:09

Mayank Singh


1 Answers

if you really want to send key value pairs to server in request body then change

urlConnection.setRequestMethod("GET");

to

urlConnection.setRequestMethod("POST");

Or if the server doesn't support POST but requires you to do GET then remove the lines

byte [] buf=("key1=" + params[0] + "&key2=" + params[1]).getBytes();
urlConnection.getOutputStream().write(buf);

As I can see from this line

URL hp=new URL("http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]);

You are already building the Url correctly for a GET Http request, but you are adding a request body to a HTTP request method that doesn't support request body (GET http method in this case).

Take a look at this wikipidea page for more details on REST and REST with HTTP/S to get a more detailed idea on this architecture

like image 158
Bhargav Avatar answered Oct 13 '22 01:10

Bhargav