2012-12-15 524 views
-1

我試圖插入MySQL數據庫經緯度值,但它顯示了以下錯誤的HTTP連接 org.apache.http連接到MySQL數據庫錯誤

  1. 錯誤。 conn.HttpHostConnectException:連接到 * 的http://本地主機拒絕 *

    //My main.java code is : 
    
    public void insertdata() 
    { 
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("Lat","34")); 
    nameValuePairs.add(new BasicNameValuePair("Lon","72")); 
    
    //http post 
    try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new  
        HttpPost("http://localhost/androidconnection/insertdata.php"); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        InputStream is = entity.getContent(); 
        Log.i("postData", response.getStatusLine().toString()); 
    } 
    
    catch(Exception e) 
    { 
        Log.e("log_tag", "Error in http connection "+e.toString()); 
    }   
    

    }

    //在服務器端我的PHP插入代碼爲 「insertdata.php」

    <?php 
        mysql_connect("localhost","root",""); 
        mysql_select_db("PeopleData"); 
        //retrieve the data 
        $lat = $_POST['lat']; 
        $lon = $_POST['lon']; 
    
        $sql = "INSERT INTO coords (Lat, Lon) VALUES('$lat', '$lon')"; 
    
         if (!mysql_query($sql, $sqlCon)) 
        { 
         die('Error: ' . mysql_error()); 
        } 
        else 
        { 
         //echo "1 record added"; 
         } 
    
          ?> 
    
+0

http://stackoverflow.com/questions/5114301/android-sdk-connect-to-web-server-on-host – 2012-12-15 08:27:12

回答

1

localhost指的是運行代碼的當前機器,在本例中是Android手機(或模擬器)。 而爲了從Android模擬器訪問主機,可以使用IP地址:10.0.2.2

更改您的網址如下:

HttpPost("http://localhost/androidconnection/insertdata.php"); 應該是這樣的:HttpPost("http://10.0.2.2/androidconnection/insertdata.php");

+0

好吧,我用你的解決方案,但現在在日誌貓我得到這個postData HTTP/1.1 200 OK while沒有數據已被插入MYSQL但 –

+0

請看我上面的評論,現在它不會給出任何錯誤,但數據不是插入數據庫 –

+0

@PirFahimShah你檢查過服務器日誌嗎?還要在你的php代碼中創建日誌點,以查看請求是否到達服務器。 – 2012-12-15 09:07:51

0

嘗試

localhost 

轉換與

web server IP Address. 

這裏, HttpPost("http://localhost/androidconnection/insertdata.php");

另請確保您已在您的Manifest文件中添加了Internet權限。

<uses-permission android:name="android.permission.INTERNET" /> 

希望它可以幫助你。

謝謝。