使用android空参数发布请求

时间:2015-05-20 17:51:31

标签: android post

我正在使用android与这个php脚本通信:我的目标是从数据库中提取用户名和密码。这是php代码:

<?php
require 'db.php';
$mysqli = new mysqli("localhost", $username, $password, $database);

if (mysqli_connect_errno()) {
    echo "Errore in connessione al DBMS: ".mysqli_connect_error();
    exit();
}
$username=$_POST['username'];
$password=$_POST['password'];
$myusername=mysql_real_escape_string($username);
$mypassword=mysql_real_escape_string($password);
//$mypassword=md5($password);
$query = "SELECT userid , image FROM `utente` WHERE username='$myusername' AND password='$mypassword' LIMIT 1";
$result = $mysqli->query($query);
if($result->num_rows >0)
{
    while($row = $result->fetch_array(MYSQLI_ASSOC))
        $rows[]=$row;
}
header("Content-type: text/json");
echo json_encode($rows);
$result->close();
$mysqli->close();
?>

用户名和密码是帖子参数。我将尝试使用URLConnection库在android中发布一个帖子请求。代码如下:

public class HTTPRequest extends AsyncTask<String, String, JSONArray> {

    @Override

    protected JSONArray doInBackground(String... params) {
        URL url;
        HttpURLConnection urlConnection = null;
        JSONArray response = new JSONArray();

        try {
            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("username","marco");
            urlConnection.setRequestProperty("password","marco");
            urlConnection.setRequestMethod("POST");


//           String username = "45dae3a1-ec1f-455a-a14b-3152001a93aa";
//            String password= "WSiwlK9q8Qeb";
//            String userpassword = username + ":" + password;
//            String encodedAuthentication = Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP);
//            urlConnection.setRequestProperty("Authorization", "Basic " +
//                    encodedAuthentication);
            urlConnection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            List<NameValuePair> paramskey = new ArrayList<NameValuePair>();
            String username="giovanni";
            String password="luca";
            paramskey.add(new BasicNameValuePair("username", username.toString()));
            paramskey.add(new BasicNameValuePair("password", password.toString()));
            //paramskey.add(new BasicN4ameValuePair("thirdParam", paramValue3));

            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(paramskey));
            //Log.i("writer",writer.toString());
            writer.flush();
            writer.close();
            os.close();
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == HttpStatus.SC_OK){
                String responseString = readStream(urlConnection.getInputStream());
                Log.i("Risposta", responseString);
                response = new JSONArray(responseString);
                String responsestrings=response.toString(1);     //for debug
                //Log.v("personalityInsightsService", responsestrings);         //for debug
            }else{
                //Log.v("personalityInsightsService", "Response code:"+ responseCode);
                return response;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(urlConnection != null)
                urlConnection.disconnect();
        }

        return response;
    }

    private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
                //Log.i(("Risposta"),line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

在主要活动中,我执行此代码来发出请求:

HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.execute("http://appmuseum.altervista.org/login.php");
        try {
            JSONArray httpResponse = httpRequest.get();
            if(httpResponse != null)
                Log.i("STRINGA",httpResponse.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

我设法通过php脚本进行通信,但是post参数用户名和密码为空,因此jsonObject post响应为空。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您不能在AsyncTask实例httpRequest上执行execute()和get()。删除.execute()之后的所有代码。永远不要做get()。添加一个onPostExecute来处理doInBackground的结果。