【问题标题】:POST data not sent via HttpURLConnectionPOST 数据未通过 HttpURLConnection 发送
【发布时间】:2016-08-17 11:57:35
【问题描述】:

我正在尝试通过 HttpURLConnection 发送 POST 请求,这是代码

public class BackgroundTask extends AsyncTask<String, Void, Void> {
    Context context;
    Activity activity;
    StringBuffer str = null;
    int responseCode;
    String responseMessage;

    public BackgroundTask(Context context) {
        this.context = context;
        this.activity = (Activity) context;
    }

    @Override
    protected Void doInBackground(String... params) {
        HttpURLConnection connection = null;

        OutputStream outputStream = null;
        InputStream inputStream = null;

        BufferedReader reader = null;
        BufferedWriter writer = null;

        String method = params[1];

        if(method.equals("post")) {
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                outputStream = connection.getOutputStream();
                writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

                String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
                writer.write(data);
                responseCode = connection.getResponseCode();
                responseMessage = connection.getResponseMessage();
                inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                str = new StringBuffer();

                String line = "";

                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null)
                    connection.disconnect();
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (writer != null) {
                    try {
                        writer.flush();
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if(method.equals("get")) {

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        TextView txt = (TextView) activity.findViewById(R.id.txt);
        if(str != null)
            txt.setText(str.toString());
        Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
    }
}

responseCode 是 200,这意味着一切正常,但它显示 Undefined index: id

id 在 php 文件中定义明确

$user = User::find_by_id($_POST['id']);
echo json_encode($user);

当我从 html 文件发送 post 请求时它工作正常,但当我从应用程序发送它时,它显示 id undefined,这意味着未发送 POST 数据。

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        BackgroundTask myTask = new BackgroundTask(MainActivity.this);
        myTask.execute(link, "post", "id", "5");
    }
});

这就是我在主要活动中实例化 asynctask 对象的方式

更新:当我发送未编码的字符串时,它工作正常! writer.write("id=5"); // 完美运行! 我在代码中使用的 URLEncoder 有什么问题?

【问题讨论】:

    标签: java android post


    【解决方案1】:

    我相信你在这行有问题:

    String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
    

    您正在对 = 以及参数进行 url 编码,这就是服务器无法识别表单字段的原因。尝试仅对参数进行编码:

    String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
    

    原因是 URL 编码是为了在值(或键)中传递特殊字符,如 =。基本上,服务器将在解码之前使用&amp;= 拆分和解析键值对。当您对= 字符进行url 编码时,服务器在拆分和解析阶段根本无法识别它。

    【讨论】:

    • 可能不需要对参数名称进行编码
    • @ScaryWombat 最好是安全的。
    【解决方案2】:

    当我需要与服务器通信时,我会使用它

    服务器类

    public static String sendPostRequest(String requestURL,
                                         HashMap<String, String> postDataParams) {
    
        URL url;
        String response = "";
        try {
            url = new URL(requestURL);
    
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
    
    
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
    
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
    
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                response = br.readLine();
            } else {
                response = "Error Registering";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return response;
    }
    
    private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");
    
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
    
        return result.toString();
    }
    

    其他类

     //Run this inside an Asynctask
     HashMap<String,String> data = new HashMap<>();
                data.put("id", id);
     String serverResponce = Server.sendPostRequest(URL,data);
    

    【讨论】:

    • writer.write("id=5"); // 完美运行! URLEncoder有问题我不知道为什么
    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 2016-09-25
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多