drl2051 2015-11-13 20:01
浏览 86

在Android / Java中使用AsyncTask发出HTTP POST请求的麻烦

In short, the problem I'm having is two-fold; my request is not posting its data to the server, and AsyncTask seems to be performing multiple times per single execution. I'll elaborate...

I'm developing an application using web-services I wrote in PHP. In my application code, I have events that trigger my request handler new HTTPRequestHandler().execute("myurl.php","POST");

The problem is almost certainly between these lines of code:

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);
     }

It quite simply does not seem to attach any URL parameters to the request, and so no data is being sent to my server. Here is my code for the RequestHandler

public class HTTPRequestHandler extends 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);
    }
}
}

I'm in the process of writing code which logs some information about the POST request, but I'll get to that once the post is actually working. My PHP looks like this:

<?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();
}
?>

and hitting this url in my browser with the url parameter &test=somevalue I can see in my database that the data is actually being posted since $_GET["test"] is not empty;

Most of the code above is from tutorials and other posts I've seen. I can't believe there's not an easier way to do this here in 2015, so if you're looking at this thinking "Why not just use this library which makes your request 5 lines of code?" please do enlighten me.

UPDATE

Ok, so now I'm trying $_POST["mykey"] in my PHP, and I've updated my Java to look like this:

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";

But I still get no post. What is a good way, using this form of code as suggested by a commenter, to get the resulting PHP response?

  • 写回答

1条回答 默认 最新

  • dousheng3364 2015-11-14 02:36
    关注

    My communication between the sending Java code and the receiving PHP code was a little mismatched. Because I'm sending JSON, I have to actually say so and json_decode the posted data. It's also important to note that although a connection may have been opened, until I read the data, the POST will not be completed.

    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";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂