在Android中使用REST-Webservices

时间:2016-05-27 20:39:04

标签: java android rest parameters httpurlconnection

我试图在Android中使用一些RESTful网络服务。我使用Jersey提供web服务,我使用HttpURLConnection用于Android客户端,我的问题是:参数没有转移到服务器。

这是我的服务器端代码:

@Path("/user")
@RequestScoped
public class UserService implements Serializable {

    @PersistenceContext
    private EntityManager em;

    public UserService() {

    }

    @POST
    @Path("/register")
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional(TxType.REQUIRED)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Integer registerUser(@QueryParam("username") String username, @QueryParam("password") String password, 
        @QueryParam("registrationToken") String registrationToken) {
        User user = new User(username, password, registrationToken);
        em.persist(user);
        System.out.println("registerUser erfolgreich aufgerufen. Userid: " + user.getId());
        return user.getId();
    }

}

对于Android客户端,我使用register-method创建了NetClient类:

public int register (String username, String password, String registrationToken) throws MalformedURLException, IOException {
    URL url = new URL(SERVER_URI + "/user/register");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    Uri.Builder builder = new Uri.Builder()
            .appendQueryParameter("username", username)
            .appendQueryParameter("password", password)
            .appendQueryParameter("registrationToken", registrationToken);
    String query = builder.build().getEncodedQuery();

    OutputStream os = connection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(query);
    writer.flush();
    writer.close();
    os.close();

    BufferedReader br = new BufferedReader(new  InputStreamReader(connection.getInputStream()));
    String response = br.readLine();
    br.close();
    Integer id = new Gson().fromJson(response, Integer.class);
    return id.intValue();
}

因此,registerUser会被调用,但如果我在registerUser-method服务器端打印我的params用户名或密码,我可以看到它们为空。 谁有人告诉我我做错了什么? 在此先感谢,感谢任何建议!

0 个答案:

没有答案