PHP的HTTP POST使用Android设备上HttpURLConnection的 [英] PHP HTTP POST on Android device using HttpURLConnection

查看:316
本文介绍了PHP的HTTP POST使用Android设备上HttpURLConnection的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:

所以,问题是,这并不发布到GoDaddy代管的在线数据库。所以我的问题是为什么,以及如何解决它有它张贴到了吗?

问题:
PHP页面不接收传递给它的名字值对。

编辑:

这是建议修改code使用HttpURLConnection类...
我已经缩小的问题岂不检索fbid。

正如你可以告诉我已经做了很多在这里我的功课......这是我的什么在postthread类被设置的logcat的这里是我的类,它的帖子:

  16 07-02:41:45.108:I / PROJECTCARUSO(12308):响应:{上岗:[空]}

HttpPostThread:

 公共类HttpPostThread继承Thread {
    公共静态最终诠释失败= 0;
    公共静态最终诠释成功= 1;
    私人URL网址;
    ArrayList的<&的NameValuePair GT;对;    公共HttpPostThread(URL SERVICE_URL,ArrayList的<&的NameValuePair GT;对,最后的处理程序处理程序)
    {
        Log.i(PROJECTCARUSO,张贴到URL:+ SERVICE_URL);
        this.url = SERVICE_URL;
        this.pairs =对;
        如果(对== NULL){
            Log.i(PROJECTCARUSO,URL PARMS为空);
            this.pairs =新的ArrayList<&的NameValuePair GT;();
        }
    }    @覆盖
    公共无效的run()
    {
        尝试{
            HttpURLConnection的康涅狄格州;
            字符串参数=;            对(NVP的NameValuePair:对){
                //你需要连接code参数的唯一值
                如果(参数==){
                    参数= nvp.getName()+=+ URLEn coder.en code(nvp.getValue(),UTF-8);
                }其他{
                    参数+ =&放大器; + nvp.getName()+=+ URLEn coder.en code(nvp.getValue(),UTF-8);
                }
            }            Log.i(PROJECTCARUSO,参数:+ param.toString());
            //创建连接
            康恩=(HttpURLConnection类)url.openConnection();
            //输出设置为true,表示你输出(上传)POST数据
            conn.setDoOutput(真);
            //一旦你设置输出为真,你并不需要设置请求方法后,但我无论如何做
            conn.setRequestMethod(POST);            // Android文档建议您将要发送到服务器的数据的长度,但
            //不要使用conn.setRequestProperty(内容长度,长度)指定此长度的头;
            //使用这个来代替。
            conn.setFixedLengthStreamingMode(param.getBytes()的长度。);
            conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            //发送POST出来
            为PrintWriter了=的新PrintWriter(conn.getOutputStream());
            的out.print(参数);
            out.close();            //建立字符串存储从服务器的响应文本
            串响应=;            //开始收听流
            扫描仪inStream中=新的扫描仪(conn.getInputStream());            //处理流并将其存储在StringBuilder的
            而(inStream.hasNextLine())
            响应+ =(inStream.nextLine());            Log.i(PROJECTCARUSO,回应:+响应);
        }
        //捕捉一些错误
        赶上(MalformedURLException的前){
            Log.i(PROJECTCARUSO,ex.toString());        }
        //和一些
        赶上(IOException异常前){            Log.i(PROJECTCARUSO,ex.toString());        }    }    公共静态布尔ISNUMERIC(字符串str)
    {
      尝试
      {
        双D = Double.parseDouble(STR);
      }
      赶上(NumberFormatException的NFE)
      {
        返回false;
      }
      返回true;
    }
}

下面是PHP的:

 < PHP//使连接
$ CON = mysqli_connect('...','...','...');
//检查连接
如果(mysqli_connect_errno()){
    的printf(连接失败:%S \\ n,mysqli_connect_error());
    出口();
}//改变分贝andriodnfp分贝
mysqli_select_db($ CON,andriodnfp');$表='用户';
的$ id = 0;$ fbid =用htmlspecialchars($ _ GET [fbid]);
$ =社会用htmlspecialchars($ _ GET [社会]);
$名称=用htmlspecialchars($ _ GET [名称]);
$ NAME =!空($名)? '$名':空;$ FNAME =用htmlspecialchars($ _ GET [FNAME]);
$ FNAME =!空($ FNAME)? '$ FNAME':空;$用户名=用htmlspecialchars($ _ GET [用户名]);
$用户名=!空($用户名)? '$用户名:NULL;$电子邮件=用htmlspecialchars($ _ GET [电子邮件]);
$电子邮件=!空($电子邮件)? '$电子邮件':NULL;$图片=用htmlspecialchars($ _ GET [图片报]);
$图片=!空($图片)? '$画面':空;$其他=用htmlspecialchars($ _ GET [等]);
$其他=!空($等)? '$等:NULL;如果(!$ fbid ==''){    如果(!mysqli_query($ CON,INSERT INTO'。$表'。(facebookID,social_outlet,名称,FIRST_NAME,用户名,电子邮件,图片,significant_other)VALUES (\"'.$fbid.'\",\"'.$social.'\",\"'.$name.'\",\"'.$fname.'\",\"'.$username.'\",\"'.$email.'\",\"'.$picture.'\",\"'.$other.'\")')) {
        的printf(ERRORMESSAGE:%S \\ n,mysqli_error($ CON));
        死();
    }其他{
        $帖=阵列('auto_increment_id'=> mysqli_insert_id($ CON));
    };
}其他{
    的printf(ERRORMESSAGE:%S \\ n,Facebook的ID为空);
    的printf(ERRORMESSAGE:%S \\ n,$ fbid);
    的printf(ERRORMESSAGE:%S \\ n,$社会的);
    的printf(ERRORMESSAGE:%S \\ n,$名);
    的printf(ERRORMESSAGE:%S \\ n,$ FNAME);
    的printf(ERRORMESSAGE:%S \\ n,$用户名);
    的printf(ERRORMESSAGE:%S \\ n,$电子邮件);
    的printf(ERRORMESSAGE:%S \\ n,$图片);
    的printf(ERRORMESSAGE:%S \\ n,$等);
    死();
}mysqli_close($ CON);// $帖=阵列($ JSON);
$帖=阵列($个);
标题(内容类型:应用程序/ JSON');
回声json_en code(阵列('职位'=> $岗位));?>

Apache日志:

  166.147.72.174  -   -  [19 /六月/下一篇:16:47:41 -0700]?POST ...... post.php中HTTP / 1.1200 155 -  Apache的HttpClient的/不可用(Java 1.4中)为0的X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php195224
166.147.72.174 - - [19 /俊/ 2013:16:49:08 -0700]?POST ...... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php13848
166.147.72.174 - - [19 /六月/下一篇:16:50:57 -0700]?POST ...... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php17899
166.147.72.174 - - [19 /俊/ 2013:16:52:14 -0700]POST ... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php12514
166.147.72.174 - - [19 /六月/下一篇:16:53:35 -0700]POST ... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php15190
166.147.72.174 - - [19 /俊/ 2013:16:54:56 -0700]POST ... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php14373
166.147.72.174 - - [19 /俊/ 2013:16:56:50 -0700]POST ... post.php中HTTP / 1.1200 155 - Apache的HttpClient的/不可用(Java 1.4中)0 X的httpd-php5-3/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php12017

编辑:

我甚至尝试了Java像​​这样:

 公共无效的run(){
    尝试{
    HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);        conn.setRequestMethod(POST);    conn.setDoInput(真);
    conn.setDoOutput(真);    清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
    对(NVP的NameValuePair:对){
    //你需要连接code参数的唯一值
        params.add(新BasicNameValuePair(nvp.getName(),nvp.getValue()));
        Log.i(PROJECTCARUSO,NVP:+ nvp.getName()+ - + nvp.getValue());
    }
    OutputStream的OS = conn.getOutputStream();
    但是BufferedWriter作家=新的BufferedWriter(
            新OutputStreamWriter(OS,UTF-8));
    writer.write(getQuery(PARAMS));
    writer.close();
    os.close();    conn.connect();    //建立字符串存储从服务器的响应文本
    串响应=;    //开始收听流
    扫描仪inStream中=新的扫描仪(conn.getInputStream());    //处理流并将其存储在StringBuilder的
    而(inStream.hasNextLine())
    响应+ =(inStream.nextLine());    Log.i(PROJECTCARUSO,回应:+响应);    }赶上(的ProtocolException E){
        // TODO自动生成catch块
        e.printStackTrace();
    }     赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
    }


解决方案

您必须使用 $ _ POST 而不是 $的_ GET 无处不在。

Question:

So the problem is that this doesn't post to the online database hosted by goDaddy. So my question is why, and how do i fix it to have it post to it?

Issue: The php page is not receiving the name value pairs being passed to it.

Edit:

Modified code on suggestion to use HttpURLConnection... I've narrowed down the problem to it not retrieving the fbid.

As you can tell I’ve done a lot of my homework here... Here's my logcat of what is being set in the postthread class Here's my class that does the post:

07-02 16:41:45.108: I/PROJECTCARUSO(12308): response: {"posts":[null]}

HttpPostThread:

public class HttpPostThread extends Thread {
    public static final int FAILURE = 0;
    public static final int SUCCESS = 1;


    private URL url;
    ArrayList<NameValuePair> pairs;

    public HttpPostThread(URL sERVICE_URL, ArrayList<NameValuePair> pairs, final Handler handler)
    {
        Log.i("PROJECTCARUSO", "Posting to URL: " + sERVICE_URL);
        this.url =sERVICE_URL;
        this.pairs = pairs;
        if(pairs==null){
            Log.i("PROJECTCARUSO", "URL parms were null");
            this.pairs = new ArrayList<NameValuePair>();
        }
    }

    @Override
    public void run()
    {
        try {
            HttpURLConnection conn;
            String param="";

            for (NameValuePair nvp : pairs) {
                //you need to encode ONLY the values of the parameters
                if (param == "") {
                    param=nvp.getName() + "=" + URLEncoder.encode(nvp.getValue(),"UTF-8");
                } else {
                    param+= "&" + nvp.getName() + "=" + URLEncoder.encode(nvp.getValue(),"UTF-8");
                }
            }

            Log.i("PROJECTCARUSO", "param: " + param.toString());
            // Create connection
            conn=(HttpURLConnection)url.openConnection();
            //set the output to true, indicating you are outputting(uploading) POST data
            conn.setDoOutput(true);
            //once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway
            conn.setRequestMethod("POST");

            //Android documentation suggested that you set the length of the data you are sending to the server, BUT
            // do NOT specify this length in the header by using conn.setRequestProperty("Content-Length", length);
            //use this instead.
            conn.setFixedLengthStreamingMode(param.getBytes().length);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //send the POST out
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.close();

            //build the string to store the response text from the server
            String response= "";

            //start listening to the stream
            Scanner inStream = new Scanner(conn.getInputStream());

            //process the stream and store it in StringBuilder
            while(inStream.hasNextLine())
            response+=(inStream.nextLine());

            Log.i("PROJECTCARUSO","response: " + response);
        }
        //catch some error
        catch(MalformedURLException ex){  
            Log.i("PROJECTCARUSO", ex.toString());

        }
        // and some more
        catch(IOException ex){

            Log.i("PROJECTCARUSO", ex.toString());

        }

    }

    public static boolean isNumeric(String str)  
    {  
      try  
      {  
        double d = Double.parseDouble(str);  
      }  
      catch(NumberFormatException nfe)  
      {  
        return false;  
      }  
      return true;  
    }
}

Here's the php:

        <?php 

//Make connection
$con = mysqli_connect('...','...','...') ;


//check connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//change db to andriodnfp db
mysqli_select_db($con, 'andriodnfp');

$table= 'USER';
$id=0;

$fbid = htmlspecialchars($_GET["fbid"]);
$social = htmlspecialchars($_GET["social"]);


$name = htmlspecialchars($_GET["name"]);
$name = !empty($name) ? "'$name'" : "NULL";

$fname = htmlspecialchars($_GET["fname"]);
$fname = !empty($fname) ? "'$fname'" : "NULL";

$username = htmlspecialchars($_GET["username"]);
$username = !empty($username) ? "'$username'" : "NULL";

$email = htmlspecialchars($_GET["email"]);
$email = !empty($email) ? "'$email'" : "NULL";

$picture = htmlspecialchars($_GET["picture"]);
$picture = !empty($picture) ? "'$picture'" : "NULL";

$other = htmlspecialchars($_GET["other"]);
$other = !empty($other) ? "'$other'" : "NULL";

if (!$fbid == '') {

    if (!mysqli_query($con, 'INSERT INTO '.$table.' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("'.$fbid.'","'.$social.'","'.$name.'","'.$fname.'","'.$username.'","'.$email.'","'.$picture.'","'.$other.'")')) {
        printf("Errormessage: %s\n", mysqli_error($con));
        die();
    } else {
        $posts = array('auto_increment_id'=>mysqli_insert_id($con));
    };
} else {
    printf("Errormessage: %s\n", "Facebook ID was null");
    printf("Errormessage: %s\n", $fbid );
    printf("Errormessage: %s\n", $social);
    printf("Errormessage: %s\n", $name);
    printf("Errormessage: %s\n", $fname);
    printf("Errormessage: %s\n", $username);
    printf("Errormessage: %s\n", $email);
    printf("Errormessage: %s\n", $picture);
    printf("Errormessage: %s\n", $other);
    die();
}

mysqli_close($con);

//$posts = array($json);
$posts = array($posts);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));

?>

Apache logs:

166.147.72.174 - - [19/Jun/2013:16:47:41 -0700] "POST ...post.php? HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 195224
166.147.72.174 - - [19/Jun/2013:16:49:08 -0700] "POST ...post.php? HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 13848
166.147.72.174 - - [19/Jun/2013:16:50:57 -0700] "POST ...post.php? HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 17899
166.147.72.174 - - [19/Jun/2013:16:52:14 -0700] "POST ...post.php HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 12514
166.147.72.174 - - [19/Jun/2013:16:53:35 -0700] "POST ...post.php HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 15190
166.147.72.174 - - [19/Jun/2013:16:54:56 -0700] "POST ...post.php HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 14373
166.147.72.174 - - [19/Jun/2013:16:56:50 -0700] "POST ...post.php HTTP/1.1" 200 155 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)" 0 "x-httpd-php5-3" "/var/chroot/home/content/31/9124131/html/android/com.projectcaruso/naturalfamilyplaning/post.php" 12017

EDIT:

I even tried the java as so:

public void run() {
    try {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);

        conn.setRequestMethod("POST");

    conn.setDoInput(true);
    conn.setDoOutput(true);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    for (NameValuePair nvp : pairs) {
    //you need to encode ONLY the values of the parameters
        params.add(new BasicNameValuePair(nvp.getName(), nvp.getValue()));
        Log.i("PROJECTCARUSO", "NVP: " + nvp.getName() + " - " + nvp.getValue());
    }


    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.close();
    os.close();

    conn.connect();

    //build the string to store the response text from the server
    String response= "";

    //start listening to the stream
    Scanner inStream = new Scanner(conn.getInputStream());

    //process the stream and store it in StringBuilder
    while(inStream.hasNextLine())
    response+=(inStream.nextLine());

    Log.i("PROJECTCARUSO","response: " + response);

    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

     catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

解决方案

You have to use $_POST instead of $_GET everywhere.

这篇关于PHP的HTTP POST使用Android设备上HttpURLConnection的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆