簡體   English   中英

將Android App連接到寧靜的Web服務

[英]Connect Android App to restful webservice

我知道這個問題已經問了很多次了,但是我找不到正確的答案,希望你們中的一個能幫助我;-)

我正在嘗試通過智能手機設備上的android應用程序與其他Web服務進行通信(因此沒有模擬器)。 該Web服務在Windows計算機上的192.168.0.2:8080上運行。 設備與PC連接在相同的局域網中。 在使用設備的Chrome瀏覽器打開鏈接時,Web服務會正常響應。

這是我用來在AsyncTask中連接到Web服務的代碼:

    protected Integer doInBackground(String... params)
    {
        try
        {
            AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
            HttpPost post = new HttpPost(params[0]);
            String xml = new ScoreDto(new Random(System.currentTimeMillis()).nextLong()).toXml();
            post.setEntity(new StringEntity(xml));
            return client.execute(post).getStatusLine().getStatusCode();
        }
        catch (Exception e)
        {
            Log.e(TAG, e.getLocalizedMessage());
            return 0;
        }
    }
  • 我嘗試使用幾種不同的方法進行連接,總是導致連接超時
  • 我在我的應用程序中包含了互聯網許可。
  • 我暫時停用了Windows pc上的本地防火牆。
  • 我嘗試了設備的端口轉發
  • 我嘗試從應用程序httpbin.org/ip調用其他Web服務,並獲得有效的響應。

有任何想法嗎? 問題似乎已連接到本地網絡。如果我想通過我的android設備連接到外部服務器,是否需要特殊的限制或權限? 提前致謝 ;-)

感謝所有發表評論以尋求幫助的人。
我發現了什么地方出了問題:
發布請求缺少content-type標題...

一個功能齊全的doBackground -Implementation如下所示:

protected Integer doInBackground(String... params)
{
    try
    {
        //TODO check if params.length >=2 & not empty
        AndroidHttpClient client = AndroidHttpClient.newInstance("androidClient", getContext());
        HttpPost post = new HttpPost(params[0]);
        post.setHeader("content-type", "application/xml");
        post.setEntity(new StringEntity(params[1]));
        return client.execute(post).getStatusLine().getStatusCode();
    }
    catch (Exception e)
    {
        Log.e(TAG, e.getLocalizedMessage());
        return 0;
    }
}

暫無
暫無

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

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