我编写了一种简单的方法来将数据发布到URL并使用输出。我尝试了多种方法消耗消耗的能量,但还没有成功:
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();
}
- 我必须将方法包装在可运行的内部,不能期望可运行的方法返回值。
- 我尝试在可运行内部的就绪状态下使用输出,但是我需要调用第三方方法来传递输出。我发现可通话,但是它不接受参数。
- 我已经阅读了accepted answer here,但是它需要为每个方法定义一个新的类。
- 我已阅读this Q/A,但建议您定义一个接口,而不是定义我认为不合适的接口方法。
如果此方法不是调用和使用url的正确方法,那么如何在应用程序中管理多个客户端-服务器请求?您是否针对每种类型的请求重写以上代码?您是否真的为每次客户服务器互动定义了新类或新接口?