「已注销」 2016-07-06 06:43 采纳率: 0%
浏览 909

简单写了一个网络请求的函数,想请教一下返回值的问题。。

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();呢?求大神解惑!!

  • 写回答

1条回答 默认 最新

  • WsoftBoy 2016-07-06 06:51
    关注

    为什么要加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  等都是不错的选择
    
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿