简体   繁体   中英

Calling REST web services from android client

I am implementing RESTful webservices at the back-end of android app.Since i am new to REST and web-services,please help in performing POST requests to my backend REST web-services.

Can i use the following code in android client to invoke the RESTful web service for POST request(by using the code in AsyncTask)?

If not,please suggest me alternatives. Any links to sample codes and resources is appreciated!! Thanks in advance ...

 package com.javacodegeeks.enterprise.rest.jersey.jerseyclient;

    import com.javacodegeeks.enterprise.rest.jersey.Student;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;
    import com.sun.jersey.api.json.JSONConfiguration;

    public class JerseyClient {

        public static void main(String[] args) {
            try {

                Student st = new Student("Adriana", "Barrer", 12, 9);

                ClientConfig clientConfig = new DefaultClientConfig();

                clientConfig.getFeatures().put(
                        JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

                Client client = Client.create(clientConfig);

                WebResource webResource = client
                        .resource("http://localhost:9090/JerseyJSONExample/rest/jsonServices/send");

                ClientResponse response = webResource.accept("application/json")
                        .type("application/json").post(ClientResponse.class, st);

                if (response.getStatus() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + response.getStatus());
                }

                String output = response.getEntity(String.class);

                System.out.println("Server response .... \n");
                System.out.println(output);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

I haven't tested your code so not sure if it works. However this is my way of doing, you can try it out:

private String sendPostRequest(String payload, String url) {
    StringEntity en = new StringEntity(payload);
    HttpPost request = new HttpPost(url);
    request.setHeader("Content-Type", "application/json");
    request.setEntity(en);

    HttpResponse httpResponse = httpClient.execute(request);
    HttpEntity entity = httpResponse.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream inputStream = bufHttpEntity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    String response = "";
    StringBuilder stringBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line);
    }
    inputStream.close();
    response = stringBuilder.toString();
    return response;
}

Check the retrofit library , it is well suited for mobile REST client. Here is how to use it: First declare your endpoints, like this:

public interface RestClient {
    @POST("/post.php")
    void postStudent(
            @Field("firstname") String firstname, 
            @Field("lastname") String lastname,
            @Field("birthday") String birthday,
            Callback<Response> callback);
}

Then create the client endpoit to use for interacting with your backed:

RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://your_server_address/")
            .setRequestInterceptor(requestInterceptor).build();
RestClient client = restAdapter.create(RestClient.class);

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