如何使用Post方法从android类执行php文件

时间:2014-07-22 06:40:12

标签: php android

我想从android执行php url并在执行url时传递这两个值。

这是我使用的代码。我使用GET方法,但我需要将其作为POST变量发送。

如何在以下代码中将请求从GET变量更改为POST变量:

public class AsyncTaskOperation extends AsyncTask <String, Void, Void>
{

    @Override
    protected Void doInBackground(String... paramsObj)
    {

        //Sending the php file path 
        String php_send="http://localhost/tested/test/copy_fiel.php?Cus="+Cus+"&"+"Cut_fol="+Cut_fol;

        System.out.println(php_send);
        // want to execute the above path using Http client but it is not working 
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(php_send);

        try {   
            HttpResponse resp = client.execute(httpGet);
            System.out.println(resp);        
        }         
        catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

2 个答案:

答案 0 :(得分:2)

将NameValuePair与HttpPost一起使用,它将起作用:

   HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://www.yoursite.com/myexample.php");

try {

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("Cus", Cus));
    nameValuePairs.add(new BasicNameValuePair("Cut_fol", Cut_fol));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


    HttpResponse response = httpclient.execute(httppost);

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

答案 1 :(得分:2)

我使用的是Asynchttp客户端。我发现设置帖子或获取

更容易

发布数据: - 创建参数对象, - 输入你的价值并发布到网址。

代码示例如下:

AsyncHttpClient client = new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("msg","Hello world");
url="[Your URL]";
client.post(url,params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onStart() {
                        super.onStart();                                                
                    }
                   @Override
                    public void onSuccess(String response) {
                    }
                    @Override
                    public void onFailure(Throwable e, String response) {
                    }
  );

你可以在这里找到图书馆

http://loopj.com/android-async-http/