在Android / Java中使用AsyncTask发出HTTP POST请求的问题

时间:2015-11-13 20:01:55

标签: java php android android-asynctask

简而言之,我遇到的问题是双重的;我的请求不是将其数据发布到服务器,并且AsyncTask似乎每次执行多次执行。我会详细说明......

我正在使用我在PHP中编写的Web服务开发应用程序。在我的应用程序代码中,我有触发请求处理程序new HTTPRequestHandler().execute("myurl.php","POST");

的事件

这些代码行之间的问题几乎可以肯定:

try {
     json.put("test", uri[1]);
     Log.d("Testing", uri[1]);
     StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
     httpPost.setContentType("application/json");
     post.setEntity(httpPost);
     httpclient.execute(post);
     result = "Success";
     } catch (JSONException e) {
         //some Error logging(e);
     }

它很简单似乎没有将任何URL参数附加到请求,因此没有数据发送到我的服务器。这是RequestHandler的代码

public class HTTPRequestHandler扩展了AsyncTask {

final String key = "?key=verylongkey";

@Override
public String doInBackground(String... uri) {
    String verb = uri[1];

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    InputStream inputStream = null;
    StringBuilder stringbuilder = new StringBuilder();

    String result = null;

//begin GET request
    if(verb.equals("GET")){
        //functional code for get; prints desired results
        }

//begin POST request
    }else if(verb.equals("POST")){
        HttpPost post = new HttpPost(uri[0]+key);
        JSONObject json = new JSONObject();

        try {
            json.put("test", uri[1]);
            Log.d("Testing", uri[1]);
            StringEntity httpPost = new StringEntity(json.toString(), HTTP.UTF_8);
            httpPost.setContentType("application/json");
            post.setEntity(httpPost);
            httpclient.execute(post);
            result = "Success";

        } catch (JSONException e) {
            Log.e("Testing", "Execution failure: exception: ", e);
        } catch (UnsupportedEncodingException e){
            Log.e("Testing", "Execution failure: exception: ", e);
        } catch (ClientProtocolException e) {
            Log.e("Testing", "Execution failure: exception: ", e);
        } catch (IOException e) {
            Log.e("Testing", "Execution failure: exception: ", e);
        }

        //endregion
    }else{
        result = "no valid method specified";
    }

    return result;
}

@Override
public void onPostExecute(String result){
    super.onPostExecute(result);
    JSONObject jsonObject;

    try {
        jsonObject = new JSONObject(result);
        List<String> stuff =new ArrayList<String>();
        JSONArray cast = jsonObject.getJSONArray("Results");

        for (int i=0;i<cast.length();i++){
            JSONObject json_data = cast.getJSONObject(i);
            Log.d("Testing", "Array["+i+"]"+json_data.getString("mykey"));
        }
    }catch(JSONException e) {
        Log.e("Testing", "Execution failure: exception: ", e);
    }
}
}

我正在编写代码,记录有关POST请求的一些信息,但是一旦帖子实际工作,我就会知道。我的PHP看起来像这样:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('default_charset', 'UTF-8');

//non-empty credential strings
$server = '';
$user = '';
$pass = '';
$dbname = '';

if ($_GET['key'] == "HwLpn88NZcb8LaCYTKaLFRpUZuGRfP92HB8DJYQvdPQEeKZWBNDkprnfzmzjP8cMsUJCpvXb") {  
    $con = mysqli_connect($server, $user, $pass, $dbname);
    if (!$con) {
        die("Connection failure: " . $con -> connect_error);
    } else {
        if (!empty($_GET["test"])) {

            $value = $_GET["test"];
            echo $value;

            $insert = mysqli_query($con, "INSERT INTO table (column) VALUES ('$value')");
            if($insert){
                echo "inserted";
            }
        } else {
            //assume functional non-post request code which prints desired data
        }
    }
    $con -> close();
}
?>

并使用url参数&test=somevalue在我的浏览器中点击此网址我可以在我的数据库中看到数据实际上已发布,因为$_GET["test"]不为空;

上面的大部分代码来自我见过的教程和其他帖子。我不敢相信在2015年这里没有更简单的方法可以做到这一点,所以如果你正在考虑这个想法“为什么不使用这个库让你的请求有5行代码呢?”请赐教。

更新

好的,现在我在我的PHP中尝试$_POST["mykey"],并且我已将Java更新为:

JSONObject json = new JSONObject();
    json.put("test","65481");

     url = new URL (uri[0]+key);
     urlConn = url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     urlConn.setRequestProperty("Content-Type", "application/json");
     urlConn.setRequestProperty("Host", "android.schoolportal.gr");
     urlConn.connect();

     // as per the suggested comment
     printout = new DataOutputStream(urlConn.getOutputStream());
     byte[] data=json.toString().getBytes("UTF-8");
     printout.write(data);

     printout.flush();
     printout.close();

     result="Post Success";

但我仍然没有发帖。使用评论者建议的这种代码形式获得最终的PHP响应有什么好方法?

1 个答案:

答案 0 :(得分:0)

我在发送Java代码和接收PHP代码之间的沟通有点不匹配。因为我发送了JSON,所以我必须这样说并json_decode发布的数据。同样重要的是要注意虽然可能已打开连接,但在我读取数据之前,POST将无法完成。

<强> PHP

if (file_get_contents('php://input') != false) {

    $data = json_decode(file_get_contents('php://input'), true);
    $value = $data["test"];
    echo $value;

    $insert = mysqli_query($con, "INSERT INTO mytable (mycolumn) VALUES ('$value')");

    if($insert){
        echo "Success";
}

<强> JAVA

JSONObject json = new JSONObject();
json.put("test","65481");

url = new URL (uri[0]+key);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.connect();

printout = new DataOutputStream(urlConn.getOutputStream());
byte[] data=json.toString().getBytes("UTF-8");
printout.write(data);

input = new DataInputStream(urlConn.getInputStream());
StringBuffer inputLine = new StringBuffer();
String tmp;

//it seems until input.readLine() is called, the POST would not execute
while ((tmp = input.readLine()) != null){
    inputLine.append(tmp);
    Log.d("Testing","Contents:"+tmp);
}

printout.flush();
printout.close();

result="Post Success";