[英]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;
}
}
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.