无法使用HttpClient从Android消费REST服务

时间:2013-01-04 16:47:02

标签: android google-app-engine rest httpclient

我正在实现GAE中托管的RESTful服务,试图将数据保存到数据存储区。

@Path("/db")
public class DBAccess {

    private static final Logger log = Logger.getLogger(DBAccess.class.getName());

    // Allows to insert contextual objects into the class,
    // e.g. ServletContext, Request, Response, UriInfo
    @Context
    UriInfo uriInfo;
    @Context
    Request request;

    @POST
    @Produces(MediaType.TEXT_HTML)
    @Consumes(MediaType.APPLICATION_JSON)
    public void saveDataBase(final List<User> data,
            @Context HttpServletResponse servletResponse,
            @Context HttpServletRequest servletRequest) throws IOException {

        log.info("saveDatabae REST Service has been called.");

        Key dbKey = KeyFactory.createKey("DataBase", "default");

        Entity user;
        DatastoreService datastore = DatastoreServiceFactory
                .getDatastoreService();

        for (int i = 0; i < data.size(); i++) {
            user = new Entity("User", dbKey);
            user.setProperty("idUser", data.get(i).getIdUser());
            user.setProperty("idGMC", data.get(i).getIdGMC());

            datastore.put(user);
        }

        servletResponse.sendRedirect("../index.jsp");
    }
}

另一方面,我有一个Android应用程序试图像

那样使用它
private static void post(String endpoint, Map<String, String> params)
            throws IOException, JSONException {

        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();

        Log.v(TAG, "Posting params to " + endpoint);

        HttpClient httpClient = new DefaultHttpClient();

        HttpPost post = new HttpPost(endpoint);

        post.setHeader("content-type", "application/json");

        // Build JSON
        JSONObject dato = new JSONObject();

        while (iterator.hasNext()) {
            Entry<String, String> param = iterator.next();
            dato.put(param.getKey(), param.getValue());
        }

        StringEntity entity = new StringEntity(dato.toString());
        post.setEntity(entity);

        HttpResponse resp = httpClient.execute(post);
        String respStr = EntityUtils.toString(resp.getEntity());

        Log.v(TAG, "HttpResponse is " + respStr);

    }

调用
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
post("http://pickapp-server.appspot.com/rest/db", params);

在GAE管理控制台中,我得到以下日志条目:

enter image description here

关键是,用户实体永远不会在GAE数据存储区中创建。我想没有调用REST服务。谁能告诉我我错过了什么?

1 个答案:

答案 0 :(得分:1)

看起来你的REST方法需要一个JSON对象数组,而Android POST提供了一个JSON对象。尝试将其包装在JSONArray