我有這樣的代碼:HttpAsyncTask不能訪問本地主機
public class Connexion extends Activity {
EditText etResponse;
TextView tvIsConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("https://10.0.2.2:29422/service/MBBS/TWVpblRlc3RJRGRlc2dlcmFldHMxNTA3MjAxNjE0MTgyMTMyMC41MzQzMjk2NDM0ODM2NDY2/customer");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
}
我已經嘗試通過模擬器這個住址給exceute:「https://10.0.2.2:29422/service/MBBS/TWVpblRlc3RJRGRlc2dlcmFldHMxNTA3MjAxNjE0MTgyMTMyMC41MzQzMjk2NDM0ODM2NDY2/customer」
我無法訪問,但與同一住址我筆記本電腦: 「https://localhost:29422/service/MBBS/TWVpblRlc3RJRGRlc2dlcmFldHMxNTA3MjAxNjE0MTgyMTMyMC41MzQzMjk2NDM0ODM2NDY2/customer」這項工作
任何idee?
爲您的計算機提供IP而不是本地主機。它會工作。 –
當我將使用模擬器此localhost地址是:10.0.2.2或? – ange
它是'10.0.2.2',但錯誤信息是什麼? – Joshua