无法将数据表单android转换为php api

时间:2019-05-26 21:54:00

标签: php android mysql

我已经使用PHP和MYSQL创建了一个API,现在我想在Android中获取数据。

如果我将静态数据传递给它并在浏览器中运行,我的API效果很好,但是当我尝试将数据发布到android时会抛出异常。我想发布mysql数据库的用户名密码和一个单词,通过该单词它将以JSON格式返回单词和定义。再次作为我提到的,当我在我的PHP脚本中添加静态数据时,它工作正常,但通过android发布时却无法正常工作。这是我到目前为止所做的

PHP
<?php
header('Content-type: application/json');

$username=urlencode($_POST["username"]);
$pass=urlencode($_POST["pass"]);
$connect = mysqli_connect('pakscrabble.ipowermysql.com', $username, $pass,'csw19');

if (!$connect) { 

die('Could not connect: ' . mysql_error());


 }

$w=urlencode($_POST["wordtosearch"]);



$q="select * from words where word='".$w."' ";


$query=mysqli_query($connect,$q); 

$dict_data = array();

while($row=mysqli_fetch_array($query)) 
{ $dict_data[] = array( 
'word' => $row[0], 
'def' => $row[1] ); 
}


echo "<pre>";
print_r(json_encode($dict_data));
echo "</pre>";

?>

Android


        String urlString = params[0]; // URL to call
        String username = params[1];
        String pass=params[2];
        String wordtosearch=params[3];

        OutputStream out = null;

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            out = new BufferedOutputStream(urlConnection.getOutputStream());

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            String data = URLEncoder.encode("username", "UTF-8")
                    + "=" + URLEncoder.encode(username, "UTF-8");

            data += "&" + URLEncoder.encode("pass", "UTF-8") + "="
                    + URLEncoder.encode(pass, "UTF-8");

            data += "&" + URLEncoder.encode("wordtosearch", "UTF-8")
                    + "=" + URLEncoder.encode(wordtosearch, "UTF-8");

            writer.write(data);
            writer.flush();
            writer.close();
            out.close();

            urlConnection.connect();
            JSONObject responseJSON = new JSONObject();
            Toast.makeText(c, String.valueOf(responseJSON.getString("def")), Toast.LENGTH_SHORT).show();
            String loginMessage = responseJSON.getString("loginMessage");
            String userName = responseJSON.getString("user");

        } catch (Exception e) {
            Toast.makeText(c, e.getMessage(), Toast.LENGTH_SHORT).show();
            return  "something happened";
        }
        return "Hello World!";

永远不会到达Hello World部分并抛出异常

0 个答案:

没有答案