Call to a Rest Webservice with a Post Request

Asked

Viewed 569 times

1

I wanted to make on Android, a call to a Rest WCF Webservice, through POST orders.

In C# I can, sending the post, url and the body param. But in the Android, whenever I send a parameter, the webservice method (although I can connect), says that the data is always invalid.

The code I have so far is this, which is the primary method of connection:

public void LoginWS(final String urlWS, final String user) throws Exception 
    {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() 
            {
                try 
                {
                   //urlWS = "http://192.168.1.25/webservice/metodoPOST

                    String inputCoded = Base64.encodeToString(user.getBytes("UTF-8"), Base64.NO_WRAP);
                    HttpURLConnection request = (HttpURLConnection) new URL(urlWS).openConnection();

                    try {
                        request.setDoOutput(true);
                        request.setDoInput(true);
                        request.setRequestProperty("Content-Type", "application/json");
                        request.setRequestMethod("POST");                        
                        request.connect();

                        InputStream is = request.getInputStream();
                        String resp = convertStreamToString(is);
                        byte[] data = Base64.decode(resp, Base64.NO_WRAP);
                        response = new String(data, "UTF-8");

                        is.close();


                    } finally {
                        request.disconnect();
                    }
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });

        thread.start();
    }

On the webservice side in WCF Rest, the signature of the method is as follows:

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,      ResponseFormat = WebMessageFormat.Json)]
    string metodoPOST(string input);

How do I submit a POST request without sending parameters with name?

1 answer

1


Miguel, to send the data you must use OutputStream. So try using the following:

Change:

InputStream is = request.getInputStream();
String resp = convertStreamToString(is);
byte[] data = Base64.decode(resp, Base64.NO_WRAP);
response = new String(data, "UTF-8");

For:

OutputStream os = request.getOutPutStream();
os.write(user.getBytes());
os.flush();
os.close();

To get the answer code:

int responseCode = request.getResponseCode();

Browser other questions tagged

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