user6951109 user6951109 - 2 days ago 5
Android Question

HTTP Post Request for Android Development - Help debugging

I am attempting to access an Apache server through a button. I am sending a message to the server and receiving a message back. I am displaying that message on a text field. My code is not working and I do not know how to debug. I am attaching my code and php script. I am a beginner at this so any help will be appreciated.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void sendMessage(View view) {

HttpURLConnection request = null;

try {
String myURL = "http://creative.colorado.edu/";
URL url = new URL(myURL);

request = (HttpURLConnection) url.openConnection();

//To post output request
request.setDoOutput(true);
request.setRequestMethod("POST");
request.setRequestProperty("message", "text/plain");

String input = "I am ok";

OutputStream outputPost = new BufferedOutputStream(request.getOutputStream());
outputPost.write(input.getBytes());
outputPost.flush();
outputPost.close();

BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}

in.close();

System.out.println(inputLine);

TextView displayMessage = (TextView) findViewById(R.id.textView2);
displayMessage.setText(in.toString());
}

catch (Exception ex) {
}

finally {
if (request != null) {
request.disconnect();
}
}

}
}


Here is the php script I am using (I am not certain it is correct):

$message);

// Send back request in JSON format
echo json_encode($returnValue);

?>

Answer

Before you read from the input stream you need to actually make the http call.

...

outputPost.close();

request.connect()

BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream())); ...

Also, any network calls need to be made in a background async thread. The Volley (https://developer.android.com/training/volley/simple.html) library makes this work dramatically easier.

Comments