duanmei1536 2016-07-10 20:13
浏览 75
已采纳

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

I am beginner to android when I send post request the string return is empty(I confirm it from the log). But when I send online post request through hurl.it it returns true(in my case which is actually right). Why it is returning empty string I don't found any mistake in my php code as well android. android code:

    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 code:

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

}

logs:

 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条回答 默认 最新

  • doushen8391 2016-07-10 20:55
    关注

    As you can see in the stack trace Your Android code is not able to reach the server hosting your PHP i.e hb99960.esy.es. Are you sure that your Android device and the PC from which you were trying out "hurl.it" is on the same network.

    Make sure you are able to reach "hb99960.esy.es" from a browser on your device/emulator.

    Hope it helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型