I want to send for example a string "hello world" through a stream to a server.
So far i did:
private void PostData() {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
}
But not sure where do i put the ip and port of the server i want to send the data to ?
Where do i put the string i want to send for example "hello world" ?
And i'm getting errors on this method:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
On the url: Cannot resolve symbol url
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
On the urlConnection.getOutputStream() unhandled exception.
On
writeStream(out);
Cannot resolve method writeStream
Same for readStream
And in the end on finally: finally without try
I took the example from the offical developers android com:
Developers android
You are totally new as I can see and that android link has some errors in the example. For every "network" work you task that you do, you have to do it asynchronously for android, also you have to add network permission to your manifest file.
For example:
Note : writeStream
and readStream
is your custom functions for the work you want them to do.
private void PostData() {
String IPPORT = "www.android.com"; // or example 192.168.1.5:80
URL url = new URL("http://"+IPPORT+"/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}
}
writeStream function example
private void writeStream(OutputStream out){
String output = "Hello world";
out.write(output.getBytes());
out.flush();
}
You can do something like :-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/plain");
String input = YOUR_INPUT_STRING;
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With