将Android中的POST数据发送到PHP

时间:2016-07-01 22:50:09

标签: php android android-activity http-post postdata

我正在寻找一种方法将POST数据发送到PHP脚本并显示结果。我想将$ username的POST数据发送给php。 这是我的php文件:

<?php

    ...// connect

            $username = $_POST['txtUsername'];// this data

    $mysqli->query("SET NAMES 'utf8'");
    $sql="SELECT * FROM $username";
    $result=$mysqli->query($sql);
    while($e=mysqli_fetch_assoc($result)){
    $output[]=$e; 
    }   

    print(json_encode($output)); 
    $mysqli->close();   

    ?>

我的活动:
DataParser.class

public class DataParser extends AsyncTask<Void,Void,Integer>{

Context c;
ListView lv;
String jsonData;

ProgressDialog pd;
ArrayList<Spacecraft> spacecrafts = new ArrayList<>();

public DataParser(Context c, ListView lv, String jsonData) {
    this.c = c;
    this.lv = lv;
    this.jsonData = jsonData;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd= new ProgressDialog(c);
    pd.setTitle("Parse");
    pd.setMessage("Parsing..Please wait");
    pd.show();
}

@Override
protected Integer doInBackground(Void... voids) {
    return this.parseData();
}

@Override
protected void onPostExecute(Integer result) {
    super.onPostExecute(result);


    pd.dismiss();
    if (result==0){
        Toast.makeText(c,"Unable to parse",Toast.LENGTH_SHORT).show();
    }
    else {
        CustomAdapter adapter = new CustomAdapter(c,spacecrafts);
        lv.setAdapter(adapter);
    }
}
private  int parseData(){
    try {
        JSONArray ja = new JSONArray(jsonData);
        JSONObject jo = null;

    spacecrafts.clear();
        Spacecraft s=null;


        for (int i=0;i<ja.length();i++){
            jo=ja.getJSONObject(i);
            int id = jo.getInt("id");
            String name =jo.getString("name");
            String send =jo.getString("send");
            String comment =jo.getString("comment");
            String date =jo.getString("date");

            s=new Spacecraft();
            s.setId(id);
            s.setName(name);
            s.setSend(send);
            s.setComment(comment);
            s.setDate(date);

            spacecrafts.add(s);
        }


        return 1;
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return 0;
}}

MainActivity:

public class MainActivity extends AppCompatActivity implements AsyncResponse {

String urlAddress="http://mysite/myphp.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ListView lv = (ListView) findViewById(R.id.lv) ;

    Intent intent = getIntent();
    final String username = intent.getStringExtra("location");

    Downloader d = new Downloader(MainActivity.this,urlAddress,lv);
    d.execute();

和Downloader.class:

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

Context c;
String urlAddress;
ListView lv;

ProgressDialog pd;
public Downloader(Context c, String urlAddress, ListView lv) {
    this.c = c;
    this.urlAddress = urlAddress;
    this.lv = lv;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd = new ProgressDialog(c);
    pd.setTitle("Fetch");
    pd.setMessage("Fetching...Please wait");
    pd.show();
}

@Override
protected String doInBackground(Void... voids) {
    return this.downloadData();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();

    if(s==null){
        Toast.makeText(c,"Unsuccessful,Null,returned",Toast.LENGTH_SHORT).show();
    }
    else {
    DataParser parser = new DataParser(c,lv,s);
        parser.execute();

    }

}


private String downloadData(){
    HttpURLConnection con = Connector.connect(urlAddress);
    if (con==null){
        return null;
    }
    InputStream is=null;
    try {

        is=new BufferedInputStream(con.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;
        StringBuffer response = new StringBuffer();

        if (br!=null){
            while ((line=br.readLine())!=null){
                response.append(line+"\n");
            }

            br.close();
        }
        else {return null;}
        return response.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if(is != null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}}

请帮帮我,谢谢!

1 个答案:

答案 0 :(得分:1)

根据您提供的代码,看起来您正在下载数据,但似乎您没有发布任何数据。

有几种方法可以通过HTTP POST发送数据。您可以尝试使用Google IO Volley API,它会为您处理大量网络呼叫逻辑。

例如:

RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://myurl.com";
JsonRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override  
        public void onResponse(JSONObject response) 
        {
            Log.d(TAG, response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Log.e(TAG, error.toString());
        }
    }) 
    {     
    @Override
    protected Map<String, String> getParams() 
    {  
        Map<String, String>  params = new HashMap<String, String>();  
        params.put("txtUsername", "mUsername");               
        return params;  
    }
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError 
    {                
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        return headers;
    }
};
queue.add(postRequest);

您也可以编写自己的AsyncTask来执行帖子。这是一个例子:

public class PostRequestAsyncTask extends AsyncTask<Void, Void, String
{
    Context context;
    Map<String, String> postParams;

    /**
     * Overridden constructor
     */
    public PostRequestAsyncTask(Context context, Map<String, String> postParams) 
    {
        this.context = context;
        this.postParams = new LinkedHashMap<String, String>(postParams);
    }

    /**
     * Default constructor
     */
    public PostRequestAsyncTask() {}

    public byte[] generatePostData() 
    {
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> dParam : postParams.entrySet())
        {
            if (postData.length() != 0) 
                postData.append('&');
            try {
                postData.append(URLEncoder.encode(dParam.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(dParam.getValue()), "UTF-8"));
            } 
            catch (UnsupportedEncodingException e) 
            {
                e.printStackTrace();
            }
        }
        byte[] postDataBytes = null;
        try 
        {
            postDataBytes = postData.toString().getBytes("UTF-8");
        } 
        catch (UnsupportedEncodingException e) 
        {
            e.printStackTrace();
        }
        return postDataBytes;
    }

    @Override
    protected String doInBackground(Void... params) 
    {
        /* Set params */
        byte[] postDataBytes = generatePostData();

        /* Set headers and write */
        URL url = null;
        HttpURLConnection conn = null;
        try 
        {
            url = new URL("https://myurl.com");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            conn.setDoOutput(true);
            conn.getOutputStream().write(postDataBytes);
        } 
        catch (MalformedURLException | IOException e) 
        {
            e.printStackTrace();
        } 

        /* Retrieve response */
        Reader in = null;
        String response = new String();
        try 
        {
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            response = "";
            for (int c = in.read(); c != -1; c = in.read()) 
            {
                response += (char) c;
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    protected void onPostExecute(String resp) {
        super.onPostExecute(resp);
        JSONObject jsonResponse = null;
        try 
        {
            jsonResponse = new JSONObject(resp);
            //do something with your json response
        } 
        catch (JSONException e) 
        {
            e.printStackTrace();
        }
    }
}

然后像这样执行AsyncTask:

Map<String, String> postParams = new LinkedHashMap<>();
postParams.put("txtUserName", "mUsername");
new PostRequestAsyncTask(MyActivity.this, postParams).execute();