How OkHttp send text data - android

I have a java code that send text file data to Label printer
through IP of LAN, It's Works fine
Can this code be executed on android using okhttp instead?
try {
FileReader fileReader = new FileReader("./src/print.txt");
BufferedReader bufferedReader=new BufferedReader(fileReader);
StringBuilder stringBuilder = new StringBuilder();
String string= "";
while((string=bufferedReader.readLine())!=null){
stringBuilder.append(string).append("\n");
}
bufferedReader.close();
Socket socket=new Socket("10.1.1.1",9100);
OutputStream outputStream=socket.getOutputStream();
outputStream.write(stringBuilder.toString().getBytes());
socket.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

No, OkHttp is a HTTP library. It uses Okio + java's Socket/SSLSocket for most of the low level IO.
The request above is just a simple TCP socket. You could use Okio operations on top of the socket if you want a nicer API.
Why not just run the code above as is on Android?

Related

post android simple app

I need a simple androd application, which POST a word to the server and recive the answer from server. I creat a form, which have two line and one button. In first line user write the word and click the button. In this time the app send this word to the server. When server send back response we show this respons in other line.
I right some code but this code don`t work on android 23. I also try to do this with retrofit, but I have varios problem with understending of this fiture.
I know that just need use POST, but don`t know how.
And can I send the ip adress of my android to the server?
Try this code:
It will also return the response from that page as a String
public static String postRequest(String post_url, String data) {
try {
URL url = new URL(post_url);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
BufferedReader br;
StringBuilder sb = new StringBuilder();
String line;
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
writer.close();
if (200 <= connection.getResponseCode() && connection.getResponseCode() <= 299) {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
}
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
And call it by:
postRequest("http://your-url", "name=value&anothername=somevalue");
I think volley will fit your needs, it's a very simple library that can handle asynchronous requests :
https://developer.android.com/training/volley/index.html
"And can I send the ip adress of my android to the server?"
Sure, to get your android ip just use a code like this on server side, assuming you're using PHP :
<?
$ip = $_SERVER["REMOTE_ADDR"];
echo "<br />Your IP is : $ip";
?>
EDIT : NodsJS example
app.post('/getip', function (req, res) {
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
})

How can i create and use only SOAP server without client on GAE?

First, sorry for my poor English.
I found this article and follow it.
https://developers.google.com/appengine/articles/soap?hl=vi
It's worked. Now i want to create only the server like that to use in other client.Is that ok?
For example when i deployed the HelloSOAPServerServlet to the abc#appspot.com
And when i want to use my service, i just paste this URL: abc#appspot.com/hellosoapserver?name=SOAP&arriving=true to the browser. How can i do something like that?
Because i want my client what use this service is the Andoird phone.
abc#appspot.com is an email address. You can not deploy GAE code to it.
When you create a GAE application you must pick a unique application name, for example mysoap. The url of your app would then be http://mysoap.appspot.com/.
After you upload your code to it you could access your SOAP at http://mysoap.appspot.com/hellosoapserver?name=SOAP&arriving=true
You got it in that example.
You made the SOAP Webservice in :
Building a SOAP Server on Google App Engine
and then you created a client that consume it from a Servlet:
Building a SOAP Client on Google App Engine Using JAX-WS
Now what you need is to make a HTTP Client call to that URL from your Android application with correct values in params.
Using the example available at http://developer.android.com/reference/java/net/HttpURLConnection.html and url provided your sample
URL url = new URL(" http://greeter-client.appspot.com/hellosoapclient?name=SOAP&arriving=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
In readStream is where you read the response from your service hosted at GAE
readStream can be something like this:
private static String readStream(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Do I need to call HttpURLConnection.disconnect after finish using it

The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage,
Do I need to call HttpURLConnection.disconnect, after finish its usage?
Do I need to call InputStream.close?
Do I need to call InputStreamReader.close?
Do I need to have the following 2 line of code : httpUrlConnection.setDoInput(true) and httpUrlConnection.setDoOutput(false), just after the construction of httpUrlConnection?
The reason I ask so, is most of the examples I saw do not do such cleanup. http://www.exampledepot.com/egs/java.net/post.html and http://www.vogella.com/articles/AndroidNetworking/article.html. I just want to make sure those examples are correct as well.
public static String getResponseBodyAsString(String request) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(request);
HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpUrlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
int charRead = 0;
char[] buffer = new char[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((charRead = bufferedReader.read(buffer)) > 0) {
stringBuffer.append(buffer, 0, charRead);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(TAG, "", e);
} catch (IOException e) {
Log.e(TAG, "", e);
} finally {
close(bufferedReader);
}
return null;
}
private static void close(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException exp) {
Log.e(TAG, "", exp);
}
}
}
Yes you need to close the inputstream first and close httpconnection next. As per javadoc.
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
Next two questions answer depends on purpose of your connection. Read this link for more details.
I believe the requirement for calling setDoInput() or setDoOutput() is to make sure they are called before anything is written to or read from a stream on the connection. Beyond that, I'm not sure it matters when those methods are called.

Socket connection getting closed while reading data from socket

I am writting simple program to connect server by socket in android.
But when i try to read data from socket's outputstream it will send automatically RST request. so my connection gets closed. but i want my connection to open always.
Please any one help me.
Thank you.
try {
Socket socket = new Socket("xxx.xxx.x.xx", 9083);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Testing");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String readObject = reader.readLine();
System.out.println(readObject);
} catch (Exception e) {
e.printStackTrace();
}
The most usual reason for 'connection reset' is that you have written to a connection that has already been closed by the other end. In other words, an application protocol error.

android socket connection, inputStream freezing on readline with socket.io or node websocket server

im using guava and weberknecht to convert an inputStream to a string and connect to a websocket [see this post]. Weberknecht threw me out, so im trying a very simple Socket-Connection to get any answer from the server. The Problem is, i can't read the inputStream. I don't know why.
NOTE:
On Iphone the Websocket-Server works. [i know "websocket /= socket" ... im just trying everything here to get ANY answer from the server]
My code:
try {
Socket sock = new Socket("62.212.88.234", 15000);
OutputStream out = sock.getOutputStream();
InputStream in = sock.getInputStream();
Log.e("SKT", "Reading input [! PROBLEM HERE !]");
String string = CharStreams.toString(new InputStreamReader(in,
"UTF-8"));
Log.e("SKT", "Answer [! NEVER REACHED !]:" + string);
sock.close();
} catch (UnknownHostException e) {
Log.e("SKT", "UnknownHostException: " + e.getMessage());
} catch (IOException e) {
Log.e("SKT", "IOException: " + e.getMessage());
}
Thanks for the Help in advance.
The documentation for CharStreams.toString says:
Reads all characters from a Readable object into a String.
My guess is that the remote end does not close the socket, so there's no end-of-stream to consume, thus the freeze.

Categories

Resources