0

我本质上是在尝试通过 Android 应用程序来模仿这里所做的事情,但由于某种原因,它在尝试发布数据时不会立即返回数据(当我删除writer.write(finalResult)行时它返回正常)。

我现在想要的只是在发送用户名后能够搜索用户的数据。

下面是我的代码:

try {
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("POST");
        c.setRequestProperty("Content-length", "0");
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.setDoInput(true);
        c.setDoOutput(true);

        //Attempting to send data!
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", paramValue));

        OutputStream os = c.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        String finalResult = getQuery(params);
        Log.d("params", finalResult);
        writer.write(finalResult);
        writer.close();
        os.close();

        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                result = sb.toString();
        }



    } catch (MalformedURLException ex) {
        Log.e("log_tag", "Error converting result ");
    } catch (IOException ex) {
        Log.e("log_tag", "Error in http connection ");
    }
    //json code!
    //parse json data
    try{
        JSONArray jArray = new JSONArray(result);
        //for each object in our json array
        for(int i =0; i < jArray.length(); i++){
            JSONObject json_data =jArray.getJSONObject(i);
            String address = "";
            //Checks for missing data in address - Need a class for all fields
            if (json_data.isNull("address")){
                address = "N/A";            
            }
            else
            {
                address = json_data.getString("address");;
            }
            //read one line of the response
            myListView.setText("Username: "+json_data.getString("username")
                    +" / " + "Name: " + json_data.getString("name")
                    +" / " + "E-mail: " + json_data.getString("email")
                    +" / " + "Address: " + address);
            }
        }
        catch(JSONException e){
            Log.e("log_tag", "Error parsing data"+e.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();
}

这是我的 php 脚本:

<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;

$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());

$query = "SELECT * FROM testusers";
$sth = mysql_query($query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query."\n";
    echo mysql_error(); 
}
else
{
    $rows = array();
    while ($r = mysql_fetch_assoc($sth)){
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>
4

2 回答 2

1

由于您将标头设置Content-Length为 0,服务器甚至不会读取您的内容......所以您发送的任何内容都不会收到。你应该设置Content-LengthfinalResult.length().

于 2013-07-09T09:05:03.080 回答
0

删除这个,

c.setRequestProperty("Content-length", "0");
于 2013-07-09T11:12:36.100 回答