从Android客户端调用REST Web服务

时间:2015-01-12 10:05:47

标签: android web-services rest

我正在android app的后端实现RESTful webservices。由于我是REST和Web服务的新手,请帮助我对我的后端REST Web服务执行POST请求。

我可以在android客户端中使用以下代码来调用POST请求的RESTful Web服务(通过使用AsyncTask中的代码)吗?

如果没有,请建议我替代方案。 任何链接到示例代码和资源的人都很感激!! 提前致谢 ...

 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();

            }

        }

    }

2 个答案:

答案 0 :(得分:0)

我没有测试过您的代码,所以不确定它是否有效。不过这是我的做法,你可以尝试一下:

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;
}

答案 1 :(得分:0)

检查retrofit library,它非常适合移动REST客户端。以下是如何使用它: 首先声明你的端点,如下所示:

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

然后创建客户端endpoit以用于与支持的交互:

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