2015-04-10 4 views
0

Я пытаюсь подключиться к xampp localhost crough android-эмулятору, используя андроид-студию. но я всегда получаю сообщение об ошибке отказа.Android to XAMPP Connection Refused

Я прочитал и попробовал большинство решений, таких как изменение localhost на 10.0.2.2 или 127.0.0.1 или 192.168.0.1, и даже попытался удалить http: // или добавить порт: 8080 за ним. но все равно не повезло.

Я могу запустить localhost/test.php в браузере без проблем. но 10.0.2.2/test.php не работает.

и, конечно же, я добавил интернет-разрешение на manifest.xml тоже.

Я даже попробовал 2 варианта кода, но мне все равно не удалось. может ли кто-нибудь помочь мне понять это?

приведена приведенная ошибка.

04-10 02:55:15.933 2162-2178/com.example.kitd16.myapplication W/System.err﹕ java.net.ConnectException: failed to connect to /10.0.0.2 (port 80) after 60000ms: isConnected failed: ECONNREFUSED (Connection refused) 

вот код, который я пробовал.

URL url = new URL("http://127.0.0.1/cloudtest/test.php"); 

          HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

          conn.setReadTimeout(30000 /* milliseconds */); 
          conn.setConnectTimeout(60000 /* milliseconds */); 
          conn.setDoOutput(true); 
          conn.setRequestMethod("POST"); 
          conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
          conn.setRequestProperty("charset", "utf-8"); 
          conn.setRequestProperty("Content-Length", "" + et.getText().toString()); 
          conn.setUseCaches(false); 
          conn.setInstanceFollowRedirects(false); 
          conn.setDoInput(true); 

          //Send request 
          DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 
          wr.writeBytes(et.getText().toString()); 
          wr.flush(); 
          wr.close(); 
          // Starts the query 
          conn.connect(); 
          is = (BufferedInputStream) conn.getInputStream(); 

         } catch (Exception ex) { 
          System.out.println("first error"); 
          ex.printStackTrace(); 
          System.exit(0); 
         } finally { 
          if (is != null) { 
           try { 
            is.close(); 
           } catch (Exception ex) { 

           } 
          } 
         } 

вторая версия

b.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server"); 
      Thread thread = new Thread() 
      { 
       @Override 
       public void run() { 
        try{ 

         httpclient=new DefaultHttpClient(); 
         httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct. 
         //add your data 
         nameValuePairs = new ArrayList<NameValuePair>(1); 
         // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
         nameValuePairs.add(new BasicNameValuePair("Edittext_value",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; 
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
         //Execute HTTP Post Request 
         response=httpclient.execute(httppost); 

         ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
         final String response = httpclient.execute(httppost, responseHandler); 
         System.out.println("Response : " + response); 
         runOnUiThread(new Runnable() { 
           public void run() { 
            p.dismiss(); 
            tv.setText("Response from PHP : " + response); 
           } 
          }); 

        }catch(Exception e){ 

         runOnUiThread(new Runnable() { 
          public void run() { 
           p.dismiss(); 
          } 
         }); 
         System.out.println("Exception : " + e.getMessage()); 
        } 
       } 
      }; 

      thread.start(); 
+1

127.0.0.1 не будет работать на эмуляторе попробовать 10.0.0.2, любезно ваш журнал в вашем вопросе , можете ли вы получить доступ к одному и тому же файлу php с помощью своего браузера –

+0

Я думаю, вы добавили интернет-разрешение в файл манифеста – pkBhati

+0

попробовали 10.0.0.2 и да, я добавил его. все еще не работает. я просто получаю ту же ошибку. –

ответ

0

Для меня, используя свой собственный IP-адрес ПК работал с Android студии эмулятора. После того, как кнопка Нажать на

HttpPost httpPost=new HttpPost("http://192.168.104.222/index.php"); 

Я использовал строгая политика режима в onCreate Метод:

protected void onCreate(Bundle savedInstanceState) { 
//Strict Mode Policy 
    StrictMode.ThreadPolicy policy =new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main_activity_login); 
    eName=(EditText)findViewById(R.id.etName); 
} 
public void Login(View v){ 

    InputStream is=null; 
    String name=eName.getText().toString(); 

    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("name",name)); 

    try{ 
     //Setting up the default http client 
     HttpClient httpClient =new DefaultHttpClient(); 
     //Setting up the http post method & passing the url in case 
     //of online database and the IP address in case of localhost database 
     //And the php file which serves as the link between the android app 
     //and the database. 
     //Second parameter is the php file to link with database 

     HttpPost httpPost=new HttpPost("http://192.168.104.222/tutorial.php"); 

     //Passing the nameValue pairs inside the httpPOST 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     //Getting the response 
     HttpResponse response =httpClient.execute(httpPost); 

     HttpEntity entity =response.getEntity(); 
     is=entity.getContent(); 

     //confirmation 
     String msg ="Data Entered Successfully"; 


    }catch(ClientProtocolException e){ 
     Log.e("ClientProtocol","Log_TAG"); 
     e.printStackTrace(); 

    }catch(IOException e){ 
     // Log.e("IO Error","Log_TAG"); 
     e.printStackTrace(); 

    } 


}