Android - POST to RESTful Web Service

2019-03-30 05:57发布

I am looking for some guidance on how to post data to a web service in my Android application. Unfortunately this is a school project, so I'm not able to use external libraries.

The web service has a base URL, for example:

http://example.com/service/create

And takes two variables, in the following format:

username = "user1"
locationname = "location1"

The web service is RESTful and uses an XML structure, if that makes a difference. From my research I understand I should be using URLconnection rather than the deprecated HTTPconnection, but I cannot find an example of what I am looking for.

Here is my attempt, which is currently not working:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toPost test = new toPost();
        text.execute();
    }

    private class toPost extends AsyncTask<URL, Void, String> {
        @Override
        protected String doInBackground(URL... params) {
            HttpURLConnection conn = null;
            try {
                URL url = new URL("http://example.com/service");
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                String body = "username=user1&locationname=location1";
                OutputStream output = new BufferedOutputStream(conn.getOutputStream());
                output.write(body.getBytes());
                output.flush();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return null;
        }
    }

}

7条回答
Anthone
2楼-- · 2019-03-30 06:54

Use below code to call rest web service from your android app. this is fully tested code.

public class RestClient {

    static Context context;
    private static int responseCode;
    private static String response;

    public static String getResponse() {
        return response;
    }

    public static void setResponse(String response) {
        RestClient.response = response;
    }

    public static int getResponseCode() {
        return responseCode;
    }

    public static void setResponseCode(int responseCode) {
        RestClient.responseCode = responseCode;
    }

    public static void Execute(String requestMethod, String jsonData, String urlMethod, Context contextTemp, HashMap<String, Object> params) {
        try {
            context = contextTemp;
            String ip = context.getResources().getString(R.string.ip);
            StringBuilder urlString = new StringBuilder(ip + urlMethod);
            if (params != null) {
                for (Map.Entry<String, Object> para : params.entrySet()) {
                    if (para.getValue() instanceof Long) {
                        urlString.append("?" + para.getKey() + "=" +(Long)para.getValue());
                    }
                    if (para.getValue() instanceof String) {
                        urlString.append("?" + para.getKey() + "=" +String.valueOf(para.getValue()));
                    }
                }
            }

            URL url = new URL(urlString.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setReadTimeout(10000 /*milliseconds*/);
            conn.setConnectTimeout(15000 /* milliseconds */);


            switch (requestMethod) {
                case "POST" : case "PUT":
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
                    conn.connect();
                    OutputStream os = new BufferedOutputStream(conn.getOutputStream());
                    os.write(jsonData.getBytes());
                    os.flush();
                    responseCode = conn.getResponseCode();
                    break;
                case "GET":
                    responseCode = conn.getResponseCode();
                    System.out.println("GET Response Code :: " + responseCode);
                    break;
                 break;

            }
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuffer tempResponse = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    tempResponse.append(inputLine);
                }
                in.close();
                response = tempResponse.toString();
                System.out.println(response.toString());
            } else {
                System.out.println("GET request not worked");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
查看更多
登录 后发表回答