The java code insert raw data into test.php, but it only works with localhost url, and don't with public ip
My urls,
//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");
Code to send data,
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 "";
}
}
My 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"
?>
I test in a real phone using 3G data and... My server is blocking in some way the public ip, because when I use the local ip it's work perfect. Blocking the writing output stream: urlConnection.getOutputStream()