简体   繁体   English

从Android客户端调用REST Web服务

[英]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. 我正在android应用程序的后端实现RESTful Web服务。由于我是REST和Web服务的新手,请在执行对我的后端REST Web服务的POST请求时提供帮助。

Can i use the following code in android client to invoke the RESTful web service for POST request(by using the code in AsyncTask)? 我可以在android客户端中使用以下代码为POST请求调用RESTful Web服务(通过使用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. 检查改造库 ,它非常适合移动REST客户端。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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