在Android中通过POST方法发送参数

时间:2017-03-25 06:55:58

标签: android post http-post

我正在开发Android应用

下面提到的是链接。

http://example.com.in/ai/abc?var=” +的 VAR

其中 var 是结果来的变量。我想在 var 中发布可用的数据以及链接。我是android的新手,所以我想知道如何在Android App中进行POST方法。

2 个答案:

答案 0 :(得分:0)

你应该这样做:

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

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        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
    }
}

答案 1 :(得分:-1)

您可以使用 Android Volley Library 将您的数据发布到您的php脚本。这是Volley Request的示例

//Declare the URL you want to send  
public static String YOUR_URL = "http://example.com.in/ai/abc?var=";

private void postDataToServer() {
    //volley request

                                                     //here you can choose your method,GET/POST,in this case is Post
    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
            YOUR_URL , null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            //if send data success do something here
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            //if having error to make request to server do something here
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //send your parameter here

            Map<String, String> parameters = new HashMap<>();
            parameters.put("yourVariable", "var");


            return parameters;
        }

        //adding header to authenticate
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String,String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            return  headers;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonReq);

}

您可以查看this tutorial,了解如何从Android发布数据并在您的php脚本中获取数据。