簡體   English   中英

如何在Android客戶端中與RESTful Web服務進行通信

[英]How to communicate to a RESTful Webservice in Android Client

我已經使用(Java + Jersey)開發了一個rest webservice ...該服務需要與用戶進行通信,即用戶需要在android客戶端應用中填寫表格並將其發送回rest webservice,然后在其中進行處理,用戶將獲得輸出...

當我第一次使用其余的Web服務時,我使用了一個Webclient ...,因此能夠以“ post”和“ get”的形式參數發送和接收請求...

但是如何在android中做同樣的事情,因為沒有表單標簽具有諸如method="post"類的屬性

我被指示使用XML解析。

更新:我知道如何從REST Web服務中以ANDROID連接和獲取數據,但如何發布它呢?

我的Form方法,它接受來自Web客戶端的響應:

@Path("/create")
    @POST
    @Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XML})
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void newUser(@FormParam("uname") String uname,
            @FormParam("password") String password,
            @Context HttpServletResponse servletResponse) throws IOException {
        boolean unamec= UserLogin.checkuname(uname);
        if (unamec) {
            // User already exists
            servletResponse.sendRedirect("http://mysite/Login.html");
        } else {
            UserLogin u = new UserLogin(uname, password);
            servletResponse.sendRedirec("http://mysite/users/"+uname+"/createnewshop");
        }
    }

我看到您請求了POST方法。 這是一個可以幫助您的代碼段。

        String urlParameters = "param_a=a&param_b=b";
        URL url = new URL("http://www.yourwebservice.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true); 
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches(false);

        // Writes the content to the web service
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(urlParameters);
        writer.flush();
        writer.close();

        // Reads the reply from the web service
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
            returnMsg += decodedString;
        }

        in.close();   
        connection.disconnect();

我只建議您使用Async Tasks連接到HTTP,這樣可以保證您的android應用程序在所有android系統中都能正常工作。

您需要Android客戶端將HTTP請求發送到您的Web服務。 看一下HttpURLConnection類。 在這里您可以找到android中HTTP客戶端的快速介紹。

Unmarshaller um;
JAXBContext jc = JAXBContext.newInstance(YourClass.class);
um = jc.createUnmarshaller();

URL url = new URL("http://localhost:8080/NutzungscodesMekacodesRESTful/rest/nc/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
YourClass obj = (YourClass) um.unmarshal(con.getInputStream());
con.disconnect();
model.setXxx(obj.getData());

另外,在這種情況下,您必須注釋您的類(YourClass.java)。 像那樣:

@XmlRootElement(name="TagName")
@XmlAccessorType(XmlAccessType.FIELD)
public class YourClassimplements Serializable
{
private static final long serialVersionUID = 1L;
@XmlAttribute
private int ID;
@XmlElement
private String name;

看看loopj吧,它建立在Apache httpclient之上,使網絡操作變得輕而易舉。 它使您可以處理json和xml,調用是異步的,並且具有get / post參數構建器,因此您可以輕松設置參數。 參見http://loopj.com/android-async-http/

根據文檔的簡單示例:

private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();

// i've skipped some of the implementation details, but in essence it boils down to this: 
client.post(url, params, responseHandler);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM