简体   繁体   English

HTTP请求和线程

[英]HTTP requests and threads

First of all I apologize for my English. 首先,我对我的英语表示歉意。

I have 2 questions about this method would be responsible for making requests POST to a PHP server. 我对此方法有2个问题,它将负责向POST请求发送到PHP服务器。

The first question is that I have an error and the application crash. 第一个问题是我有一个错误,应用程序崩溃了。 First it was because I had to create a thread and put my logic inside, but now the APP closes without showing anything. 首先是因为我必须创建一个线程并将逻辑放入其中,但是现在APP关闭时没有显示任何内容。

The second problem is that I don't know how to return as something in the thread. 第二个问题是,我不知道如何在线程中以某种形式返回。 Should to write in a variable and then return that value. 应该写一个变量,然后返回那个值。 To show the code I put a fixed return true. 为了显示代码,我将固定返回值设为true。

public boolean hacerPeticion(final String servicio, final Map params){
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            String requestURL = R.string.http_base_url + servicio;

            try {
                HttpUtility.sendPostRequest(requestURL, params);
                String response = HttpUtility.readSingleLineRespone();

                JSONObject jsonObj = parsearJSON(response);

                if(jsonObj != null){
                    int error_code;
                    try {
                        error_code = Integer.parseInt(jsonObj.getString("error"));
                    } catch(NumberFormatException nfe) {
                        error_code = 99;
                    }

                    if(error_code == 0){
                        // true;
                    }else{
                        // false;
                    }
                }else{
                    // false;
                }
            } catch (IOException ex) {
                // false;
            } catch (JSONException e) {
                // false;
            }
            HttpUtility.disconnect();
        }
    }).start();

    return true;
}

Thanks! 谢谢!

First problem 第一个问题

You are completely ignoring your errors. 您完全忽略了您的错误。 Actually print the Exception so you can see what is going wrong. 实际打印异常,以便您可以查看出了什么问题。

catch (IOException ex) {
    ex.printStackTrace();
} 

Second problem 第二个问题

Your error is most likely coming from this line because R.string.http_base_url returns an int , not a String. 您的错误很可能来自此行,因为R.string.http_base_url返回int而不是String。

String requestURL = R.string.http_base_url + servicio;

To fix that specific problem, you need a Context to get the actual string value. 要解决该特定问题,您需要一个Context来获取实际的字符串值。 For example, you could do something like this 例如,您可以执行以下操作

String requestURL = getApplicationContext().getString(R.string.http_base_url) + servicio;

Third problem 第三个问题

You are using a low-level Thread instead of an AsyncTask (or some other network library like Volley or OkHttp which make network requests easy). 您使用的是低级线程,而不是AsyncTask(或一些其他网络库,例如VolleyOkHttp ,它们使网络请求变得容易)。

There is almost never a reason to use a Java Thread in Android code. 几乎没有理由在Android代码中使用Java Thread Handler is the more correct class to use in that scenario, anyways. 无论如何, Handler是在该方案中使用的更正确的类。


Fourth problem 第四个问题

Since you are using asynchronous code, you can't simply expect a return value to comeback immediately. 由于您正在使用异步代码,因此不能简单地期望返回值立即返回。 Your method will always return true (maybe before the Thread even starts). 您的方法将始终返回true (甚至在Thread启动之前)。

The approach I recommend is to use a callback , like I've already answered before. 我推荐的方法是使用回调 ,就像我之前已经回答过的那样。

It sounds like you are talking about some kind of callback pattern. 听起来您正在谈论某种回调模式。 I guess the reason for the crash is you were blocking the UI thread causing the app to freeze , become unresponsive to the user. 我想崩溃的原因是您阻止了导致应用程序冻结的UI线程,从而对用户无响应。 This is a guess as you only give a smigit of code. 这只是一个猜测,因为您只给出了一段代码。 Implementing a callback or better yet use one built into the framework. 实现回调或更好的方法是使用框架中内置的回调。 If this is android onActivityResult is one example of a callback. 如果是android,onActivityResult是回调的一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM