public String urlCon(final String input) {
Looper.prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0 + 123) {
try {
URL url = new URL(PATH + input);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(8000);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.flush();
connection.getResponseCode();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
final StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Log.i("返回的数据是 ", response.toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {//
e1.printStackTrace();
}
}
}
};
Message message = new Message();
message.what = 0 + 123;
handler.sendEmptyMessage(message.what);
Looper.loop();
return null;
}
我的想法是如果网很卡的时候这个耗时操作应该写到HANDLE方法里面 然后就这样写了 ,在没有用handler找以前函数的返回值就是函数的运行结果response.toString()现在加了handler我返回的是一个NULL,但是我想让这个函数的返回值是重写的 handleMessage里面得到的结果response.toString() 请问这里要怎么修改才能 return response.toString();呢?求大神解惑!!
为什么要加handler呢?你可以直接返回 response.toString() 这个就是你请求的结构,当然 你不能在主线程里面做网络请求,你需要单独一个线程做网络请求 ,然后把结果返回主线程,
比如 使用AsyncTask
new AsyncTask(){
@Override
protected String doInBackground(Integer... params) {
//做网络请求,然后返回请求结果
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//返回数据到主线程
}
}.execute();
或者你可以使用一些第三方的http框架,okhttp ,volley 等都是不错的选择