当我在android中发送帖子请求时,它什么都不返回。当我向我的服务器发送post请求时,它显示写入的东西

时间:2016-07-10 20:14:00

标签: java php android post

我是初学者,当我发送post请求时,字符串返回为空(我从日志中确认)。但是当我通过hurl.it发送在线帖子请求时,它返回true(在我的情况下,这实际上是正确的)。为什么它返回空字符串我没有在我的PHP代码中发现任何错误以及android。 android代码:

    package com.example.harshitbatra.hammertime;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Harshit Batra on 06-07-2016.
 */
public class Signupasync extends AsyncTask<String, Void, String>
{
    String username,phone,address,email,password;
    String url;

    private postexecutelistener myListener;

    public Signupasync(postexecutelistener pel,String url,String username, String phone,String address,String email,String password )
    {
        myListener = pel;
        this.url = url;
        this.username = username;
        this.phone = phone;
        this.address = address;
        this.email = email;
        this.password = password;
    }

    public interface postexecutelistener
    {
        public void postexecutedone(String str);
    }

    public String connect()
    {
        HashMap<String,String> hash = new HashMap<>(6);
        hash.put("usernamekey",username);
        hash.put("phonekey",phone);
        hash.put("addresskey",address);
        hash.put("emailkey",email);
        hash.put("passwordkey",password);

        return performPostCall(url,hash);

    }

    public String performPostCall(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)
            {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null)
                {
                    response += line;
                }
            }
            else
            {
                response = "";

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

        return response;
    }
    private 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"));
        }
        Log.e("dsasd", "getPostDataString: " + result);
        return result.toString();
    }


    @Override
    protected String doInBackground(String... para)
    {
        return connect();
    }

    @Override
    protected void onPostExecute(String str)
    {
        super.onPostExecute(str);
        Log.d("jsdk", "String from signup.php " + str);
        myListener.postexecutedone(str);
    }

}   

php代码:         

$con = mysqli_connect("mysql.hostinger.in","u626717580_batra","hb99960","u626717580_mydb");


if($con)
{

    $username = $_POST['usernamekey'];
    $phone = $_POST['phonekey'];
    $address = $_POST['addresskey'];
    $email = $_POST['emailkey'];
    $password = $_POST['passwordkey'];


    $sql = "INSERT INTO  `u626717580_mydb`.`signup` (
    `username` ,
    `phone` ,
    `address` ,
    `email` ,
    `password`
    )
    VALUES (
    '$username',  '$phone',  '$address',  '$email',  '$password'
    );
    ";          

    if($username)
    {
        if(mysqli_query($con,$sql) )
        echo "true";
        else
        echo "false";   
    }

}

日志:

 W: java.net.UnknownHostException: Unable to resolve host "hb99960.esy.es": No address associated with hostname
W:     at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
W:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
W:     at java.net.InetAddress.getAllByName(InetAddress.java:214)
W:     at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
W:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
W:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
W:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
W:     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
W:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
W:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
W:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
W:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
W:     at com.example.harshitbatra.hammertime.Signupasync.performPostCall(Signupasync.java:79)
W:     at com.example.harshitbatra.hammertime.Signupasync.connect(Signupasync.java:58)
W:     at com.example.harshitbatra.hammertime.Signupasync.doInBackground(Signupasync.java:134)
W:     at com.example.harshitbatra.hammertime.Signupasync.doInBackground(Signupasync.java:26)
W:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
W:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W:     at java.lang.Thread.run(Thread.java:841)
W: Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
W:     at libcore.io.Posix.getaddrinfo(Native Method)
W:     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
W:     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
W:  ... 21 more
W: Caused by: libcore.io.ErrnoException: getaddrinfo failed: EINVAL (Invalid argument)
W:  ... 24 more    
D: String from signup.php 

 last line "String from signup.php" is empty.

1 个答案:

答案 0 :(得分:1)

正如您在堆栈跟踪中看到的那样,您的Android代码无法访问托管PHP的服务器,即hb99960.esy.es。你确定你的Android设备和你正在试用的PC&#34; hurl.it&#34;是在同一个网络上。

确保您能够到达&#34; hb99960.esy.es&#34;来自设备/模拟器上的浏览器。

希望有所帮助