Android / PHP - 努力发布数据

时间:2015-05-26 16:05:03

标签: php android

我正在努力找出问题所在。完全相同的代码适用于另一个项目。如果我将它指向上一个项目中的URL,它可以在当前项目中工作 - 但是在一个新的URL上,它只是不会发布NameValuePairs。

这就是我用来检索字符串的内容:

public static String getJSON(String url, List<BasicNameValuePair> params, int timeout) {

    String response = "";
    try {

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);

        URL uri = new URL(url);
        HttpURLConnection request = (HttpURLConnection) uri.openConnection();

        request.setUseCaches(false);
        request.setDoOutput(true);
        request.setDoInput(true);

        request.setRequestMethod("POST");
        OutputStream post = request.getOutputStream();
        entity.writeTo(post);
        post.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String inputLine = "";
        while ((inputLine = in.readLine()) != null) {
            response += inputLine;
            // res = response;
        }
        post.close();
        in.close();
    } catch (Exception e) {
        Log.e("Your app", "error", e);
    }

    return response;

}

这是我的PHP文件:

<?php

if (isset($_POST['Type'])){
    print_r($_POST);
}else {
    echo "No post received";
}

?>

这是我的要求:

            List<BasicNameValuePair> nameValuePair = new ArrayList<BasicNameValuePair>(1);
            nameValuePair.add(new BasicNameValuePair("Type", "20"));
            nameValuePair.add(new BasicNameValuePair("version", "1.3"));

            String stringArrayElement = "\n";
            String result = Config.getJSON(Config.MyUrl + "test4.php", nameValuePair, 1000);
            JSONObject JSON_DATA;

            // Making HTTP Request

            try {
                JSON_DATA = new JSONObject(result);

                Downloaded_menu_array = JSON_DATA.getJSONArray("Menu");

            }catch (JSONException e){
                e.printStackTrace();

            }

它始终击中&#34;没有收到帖子&#34;在我的PHP文件中。是否有任何与代码跳出来或我错过了其他东西?

2 个答案:

答案 0 :(得分:0)

我相信你的问题依赖于你如何调用你的php文件(在这种情况下,$(document).ready(function(){ $("li").mouseover(function(event){ $("#capa").addClass("class"); }); }); ),这将执行getJSON请求,这就是你的GET数组为空的原因。出于调试目的,在php脚本中,试试这个:

$_POST

检查你是否得到任何东西。我非常确定以下一行:

var_dump($_GET);

是空响应的根本原因。您应该尝试对脚本执行POST请求,或者通过String result = Config.getJSON(Config.MyUrl + "test4.php", nameValuePair, 1000); 方法在脚本中检索数据。

答案 1 :(得分:0)

非常尴尬。

原来是域名 - 它有一个重定向重定向http://www.domain.comhttp://domain.com,这意味着我的Config.MyUrl中的网址不正确。

它扔了我,因为它仍在击中文件 - 我只能猜测它在重定向之前点击文件并在重定向后完成处理。