http post请求在android中不起作用

时间:2014-07-03 06:55:35

标签: php android

我在android中发送了一个httpPost请求到php页面(在php页面中我使用了一个php代码将数据插入到表中。)在Android应用程序中工作正常,但在php页面中没有活动。

这是完整的代码

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0]);
        return null;
    }
    protected void onPostExecute(Double result){
        pb.setVisibility(View.GONE);
        Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
    }
    protected void onProgressUpdate(Integer... progress){
        pb.setProgress(progress[0]);
    }

    public void postData(String valueIWantToSend) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://127.0.0.1/android_connect/create_product.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

2 个答案:

答案 0 :(得分:0)

127.0.0.1不适用于模拟器。要访问localhost,请使用10.0.2.2代替127.0.0.1

使用Android设备时,请将计算机和设备连接到同一网络,然后使用计算机的IP地址访问服务器。

答案 1 :(得分:0)

在HttpPost中使用您的IP地址

 httppost= new HttpPost("http://ipaddress/android_connect/create_product.php"); 

我认为这会对你有帮助