HttpURLConnection只有localhost中的原始数据

时间:2016-11-12 05:16:57

标签: php android httpurlconnection

java代码将原始数据插入test.php,但它只适用于localhost网址,不适用于公共IP

我的网址,

//this URL work perfect, output: {"a":"b"} phpOK
postJSON("http://192.168.1.100/test.php?username=user&password=pass");

//this URL don't work, output: phpOK
postJSON("http://myddns.net/test.php?username=user&password=pass");

发送数据的代码,

public String postJSON(String URL, String jsonStr) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpURLConnection urlConnection = null;
    StringBuffer response = null;
    try {
        URL url = new URL(URL);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setFixedLengthStreamingMode(jsonStr.getBytes().length);

        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();

JSONObject jsonStr= new JSONObject();
jsonStr.put("a", "b");

        DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream());
        printout.writeBytes(jsonStr);
        printout.flush();
        printout.close();

        //if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream is = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String inputLine;
        response = new StringBuffer();

        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }
        br.close();
    } finally {
        if(urlConnection != null)
            urlConnection.disconnect();
        if(response != null)
            return response.toString();
        else
            return "";
    }
}

我的PHP,

//in test.php
<?php
 $phpInput = file_get_contents('php://input');
 echo $phpInput." phpOK";
if(isset($_GET['username']) & isset($_GET['password']))
 echo "extra vars catched"
?>

我在使用3G数据的真实手机中进行测试......我的服务器在某种程度上阻止了公共IP,因为当我使用本地IP时,它的工作非常完美。阻止写入输出流:urlConnection.getOutputStream()

1 个答案:

答案 0 :(得分:0)

我发现了问题:

问题是我的DDNS记录类型。

我使用记录类型URL配置我的ddns,协议HTTP://和IP X.X.X.X:1994

我更改为记录类型DNS主机(A),IPv4地址:仅限myip X.X.X.X,没有端口。

在我的URL客户端中,我在URL中设置了端口。

我更改了我的DDNS的记录类型, http://myddns.net/test.php?username=user&password=pass 对此: http://myddns.net:1994/test.php?username=user&password=pass