I have write a simple method to post data to URL and consume the output. I hava tried multiple ways to consume the out put but no success yet:
public void postToUrl(final String theurl, final String query, final Callable<Void> myMethod){
String urlData="";
new Thread(new Runnable() {
@Override
public void run() {
try {
String urlData="";
String url=baseurl+ theurl + "/?" +query;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.connect();
InputStream response = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
String line="";
while ((line = reader.readLine()) != null) {
urlData += line;
}
reader.close();
// How to consume urlData here?
// myMethod.call(); not accepts parameter
try {
myMethod.call(urlData);
}catch (Exception e){
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
).start();
}
- I have to wrap the method inside a runnable and can not expect a runnable method to return a value.
- I tried to consume the output when it is ready inside the runnable but I need to call a third party method to pass the output. I found callable but it does not accept parameters.
- I have read the accepted answer here but it needs to define a new class for every method.
- I have read this Q/A but it suggest to define an interface instead of method that I believe is not the proper use of interface.
If this method is not the proper way to call and consume a url, how do you manage multiple client-server request in an application? Do you rewrite the codes above for every type of request? Do you really define a new class or new interface for every clien-server interactions?