简体   繁体   中英

Send data using POST to java server from Android client and get JSON response

I am completely new to Android programming. I have come across the following problem - I want to validate the credentials of the user who uses the application. For this I want to use POST method to send the Login details to the server. From there I want to get response in JSON format. I don't know how to receive the response. I am using Java for server side programming.

PS I would deal with security concerns bit later. Following is my Android code. I know it is a mess.. Please help.

HttpURLConnection connection; OutputStreamWriter request = null;

        URL url = null;   
        String response = null;         
        String parameters = "username="+mUsername+"&password="+mPassword;   

        try
        {
            url = new URL("address");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();            
            String line = "";               
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            // Response from server after login process will be stored in response variable.                
            response = sb.toString();
            // You can perform UI operations here
            Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
            isr.close();
            reader.close();

        }
        catch(IOException e)
        {
            // Error
            return -1;
        }

There's an open source class you can use for just this, and you can easily browse the code to see how it works. There are actually many open source libs that do this, but the following is among the cleanest and easiest to work with in my opinion.

https://github.com/kevinsawicki/http-request/blob/master/lib/src/main/java/com/github/kevinsawicki/http/HttpRequest.java

And your code will probably look something like this:

Map<String, String> params = new HashMap<String, String>();
params.put("username", mUsername);
params.put("password", mPassword);
String response = HttpRequest.post(url).form(params).body();

EDIT

My original answer including the params map in to post method would have sent the request as a POST but the params in the url. The corrected version ( form method) sends the params in the body.

You can convert your json response to a JSONObject class.

Look this app, the code is very simple.

@Override
    public List<User> getRanking() {
            final List<User> result = new ArrayList<User>();
            String url = "http://quiz-exmo.rhcloud.com/rest/user/ranking/";
            String json = HttpUtil.doGet(url);
            try {
                    final JSONObject resultJsonObject = new JSONObject(json);
                    final JSONArray jsonArray = resultJsonObject.getJSONArray("users");
                    for (int index = 0, total = jsonArray.length(); index < total; index++) {
                            final JSONObject jsonObject = jsonArray.getJSONObject(index);
                            final User user = new User();
                            user.name = jsonObject.getString("name");
                            user.email = jsonObject.getString("email");
                            user.score = jsonObject.getInt("points");
                            result.add(user);
                    }
            } catch (JSONException e) {
                    throw new RuntimeException(e);
            }
            return result;
    }

https://github.com/exmo/equizmo-android/blob/master/maven/equizmo/src/main/java/br/gov/serpro/quiz/service/rest/UserServiceRest.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM