2012-03-18 79 views
1

我在android的java類中使用了以下代碼。除了不發送任何請求之外,一切都可以工作。答案始終爲空。使用HttpPost從本地服務器獲取數據

public class WebviewActivity extends Activity { 
    /** Called when the activity is first created. */ 
EditText et; Editable ur; 
TextView tx;HttpResponse response;String x; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    tx=(TextView)findViewById(R.id.textView1); 
    et=(EditText)findViewById(R.id.editText1); 
    Button button = (Button)findViewById(R.id.button1); 
    button.setOnClickListener(send); 

} 
private OnClickListener send = new OnClickListener() { 
    public void onClick(View v) { 
    ur=et.getText(); 
     postData(); 
    tx.setText("ans:"+x); 

    }}; 

public void postData() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://localhost/name.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
     nameValuePairs.add(new BasicNameValuePair("name", ur.toString())); 

     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     response = httpclient.execute(httppost); 
     Log.d("myapp", "response " + response.getEntity()); 
     x= EntityUtils.toString(response.getEntity()); 


    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} } 

,並在PHP我用下面的代碼

 <?php 
    $name=$_POST["name"]; 
     echo $name; 
    ?> 

任何想法如何使它發揮作用?

+0

你有設備上或計算機上的服務器嗎? – MByD 2012-03-18 09:19:35

+0

是的,我做..我使用IIS 7與PHP啓用..所有其他的PHP應用程序工作正常 – 2012-03-18 09:30:44

回答

0

您必須在模擬器上使用IP地址10.0.2.2作爲localhost。

+0

philip:它將如何傳輸數據到IIS? – 2012-03-18 10:19:05

+0

謝謝你philip它的工作:) – 2012-03-18 10:24:17