-1
我正在寫一個android應用程序,該應用程序應該連接到我編寫的Web服務,但每當我嘗試在模擬器上測試它時,都會在應用程序進入HttpUrlConnection.connect()行:繼承我的代碼。引發的異常是java.net.ConnectException:未能連接到本地主機/ 127.0.0.1(端口8080):連接失敗:ECONNREFUSED(連接被拒絕)。提前感謝任何能夠解決此問題的人。Expeption在Android模擬器的HttpUrlConnection.connect()
private class LongOperation extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
Log.d ("8","entered into doInBackground");
String Content;
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject json = new JSONObject();
json.put("function","getData");
json.put("id", 1);
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
Content = conn.getInputStream().toString();
return Content;
}
catch(Exception ex)
{
Log.d ("9","entered into do in background exception");
ex.printStackTrace();
return null;
}
}
protected void onPostExecute(String Content) {
try {
readJsonStream(Content);
} catch (Exception e) {
Log.d("ReadPositionJSONFeedTask", e.getLocalizedMessage());
}
}
}
我遇到了一些問題,瞭解如何我應該繼續:在我的代碼中,我要求連接到一個類似的URL:「http:/ localhost:8080/ecc ...」。意思是我應該把這個URL中的本地主機改爲10.0.2.2?因爲它不工作,並且我收到的日誌是java.io.FileNotFoundException:http://10.0.2.2:8080/... –
是的,而是localhost:8080或者您應該使用10.0.2.2:8080。要進行快速測試,您可以在模擬器中打開瀏覽器並打開http://10.0.2.2:8080。如果您收到答案,則問題出現在您的代碼中,否則在您的Web服務器中有問題。 –