繁体   English   中英

如何使用AsyncTask向目标发送多个请求<String, Void, String>

[英]How to send multiple requests to the target with AsyncTask<String, Void, String>

我连接到一个网站并执行阅读器,然后更新了textView。 这仅适用于一项。如何向网站发送多个请求? 这是我在做什么<请参考代码>

public class MainActivity extends AppCompatActivity {

    int counter = 0;
    TextView textViewGMT;
    TextView textViewCET;
    TextView textViewCN;
    TextView textViewKR;
    TextView textViewIST;
    String[] cities = {"London","Paris","Beijing","Seoul","Delhi"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewGMT = findViewById(R.id.textViewGMT);
        textViewCET = findViewById(R.id.textViewCET);
        textViewCN = findViewById(R.id.textViewCN);
        textViewKR = findViewById(R.id.textViewKR);
        textViewIST = findViewById(R.id.textViewIST);


        GetTime readerTask = new GetTime();
        String cityURL;
        for ( int i=0; i<cities.length; i++) {
            cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];
            readerTask = new GetTime();
            readerTask.execute(cityURL);
        }

    }
    @Override
    protected void onStop(){
        super.onStop();
        Log.i("In onsStop()", "Executing finish()");
        finish();
    }
    public class GetTime extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {

            HttpURLConnection urlConnection;
            URL url;
            String result = "";


            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while ( data != -1 ) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                counter++;
                return ( result );

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return ( "***Failed in AsyncTask MalforemedURL***");
            } catch (IOException e) {
                e.printStackTrace();
                return ( "***Failed in AsyncTask IOException***");
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("WEBSITE CONTENT: ", result);

            ArrayList<String> arrayList = new ArrayList<>();

            try {
                JSONObject jsonObject = new JSONObject(result);
                System.out.println("Before String");

                System.out.println("After String");

                String main = jsonObject.getString("time");
                arrayList.add("Date: " );
                String[] arrOfStr = main.split(" ");
                arrayList.add(arrOfStr[0]);
                arrayList.add(" ");
                arrayList.add("Time:");
                arrayList.add(arrOfStr[1]);
                String desc = jsonObject.getString("timezone");
                Log.i("***main: ", main);
                Log.i("***description: ", desc);

                arrayList.add(" " );
                arrayList.add(desc);
                arrayList.add("\n");

                String textOut = "";
                for ( String each: arrayList ){
                    System.out.println(each);
                    textOut = textOut + each + "\n";
                }
               //If I could run it multiple times I can update the textViews.
               //This does not work at the moment.
                switch(counter){
                    case 0: textViewGMT.setText("London "+textOut);
                    case 1: textViewCET.setText("France "+textOut);
                    case 2: textViewCET.setText("China "+textOut);
                    case 3: textViewCET.setText("Korea"+textOut);
                    case 4: textViewCET.setText("India"+textOut);
                }
                System.out.println("TEXTOUT" + textOut);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}

这将为我提供我传入的URL /城市的时间信息。想传递一个URL并用结果更新textView,然后传递另一个并更新另一个textView或并行执行所有操作。 我该如何实现? 我需要多次实例化AsyncTask吗?

尝试循环运行阅读器,但失败。

你可以只添加你要发送到与您的网址值& 因此,请替换此行:

cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];

cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i]+"&value2=" + value2 + "&value3=" + value3;#

基本上:

网址+ + value1 = value1 value2 = value2

建议使用诸如OkHttp之类的Web框架,但是如果您坚持在此处使用AsyncTask + HttpURLConnection,请参见以下代码段:

TextView textViewGMT;
TextView textViewCET;
TextView textViewCN;
TextView textViewKR;
TextView textViewIST;
String[] cities = {"London","Paris","Beijing","Seoul","Delhi"};
List<GetTime> tasks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textViewGMT = findViewById(R.id.textViewGMT);
    textViewCET = findViewById(R.id.textViewCET);
    textViewCN = findViewById(R.id.textViewCN);
    textViewKR = findViewById(R.id.textViewKR);
    textViewIST = findViewById(R.id.textViewIST);

    tasks = new ArrayList<>(cities.length);
    String cityURL;
    for ( int i=0; i<cities.length; i++) {
        cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];
        GetTime readerTask = new GetTime();
        readerTask.execute(cityURL, positionToTextView(i), positionToCountry(i));

    }
}

private String positionToCountry(int i) {
    switch(i){
        case 0: return "London ";
        case 1: return "France ";
        case 2: return "China ";
        case 3: return "Korea";
        case 4: return "India";
    }
    return null;
}

private TextView positionToTextView(int index) {
    switch(index){
        case 0: return textViewGMT;
        case 1: return textViewCET;
        case 2: return textViewCN;
        case 3: return textViewKR;
        case 4: return textViewIST;
    }
    return null;
}

@Override
protected void onStop(){
    super.onStop();
    Log.i("In onsStop()", "Executing finish()");
    finish();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    for (GetTime getTime: tasks) {
        getTime.cancel(false);
    }
}

public static class GetTime extends AsyncTask<Object, Void, String> {

    private String countryPrefix;

    private TextView textView;

    @Override
    protected String doInBackground(Object... objects) {
        String urlStr = (String) objects[0];
        textView = (TextView) objects[1];
        countryPrefix = (String) objects[2];
        HttpURLConnection urlConnection;
        URL url;
        String result = "";

        try {
            url = new URL(urlStr);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while ( data != -1 ) {
                char current = (char) data;
                result += current;
                data = reader.read();
            }
            return ( result );

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ( "***Failed in AsyncTask MalforemedURL***");
        } catch (IOException e) {
            e.printStackTrace();
            return ( "***Failed in AsyncTask IOException***");
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.i("WEBSITE CONTENT: ", result);
        List<String> arrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(result);
            System.out.println("Before String");
            System.out.println("After String");

            String main = jsonObject.getString("time");
            arrayList.add("Date: " );
            String[] arrOfStr = main.split(" ");
            arrayList.add(arrOfStr[0]);
            arrayList.add(" ");
            arrayList.add("Time:");
            arrayList.add(arrOfStr[1]);
            String desc = jsonObject.getString("timezone");
            Log.i("***main: ", main);
            Log.i("***description: ", desc);

            arrayList.add(" " );
            arrayList.add(desc);
            arrayList.add("\n");

            String textOut = "";
            for ( String each: arrayList ){
                System.out.println(each);
                textOut = textOut + each + "\n";
            }

            if (textView != null) textView.setText(countryPrefix + textOut);
            System.out.println("TEXTOUT" + textOut);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

使用OkHttp简化网络请求:

TextView textViewGMT;
TextView textViewCET;
TextView textViewCN;
TextView textViewKR;
TextView textViewIST;
String[] cities = {"London","Paris","Beijing","Seoul","Delhi"};

List<Call> calls;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textViewGMT = findViewById(R.id.textViewGMT);
    textViewCET = findViewById(R.id.textViewCET);
    textViewCN = findViewById(R.id.textViewCN);
    textViewKR = findViewById(R.id.textViewKR);
    textViewIST = findViewById(R.id.textViewIST);

    OkHttpClient client = new OkHttpClient();
    String cityURL;
    calls = new ArrayList<>(cities.length);
    for ( int i=0; i<cities.length; i++) {
        cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];
        Request request = new Request.Builder()
                .url(cityURL)
                .build();
        Call call = client.newCall(request);
        final TextView textView = positionToTextView(i);
        final String countryPrefix  = positionToCountry(i);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!call.isCanceled()) {
                    if (textView != null)
                        textView.setText(countryPrefix + bodyToTextOut(response.body().toString()));
                }

            }
        });
        calls.add(call);
    }
}

private String positionToCountry(int i) {
    switch(i){
        case 0: return "London ";
        case 1: return "France ";
        case 2: return "China ";
        case 3: return "Korea";
        case 4: return "India";
    }
    return null;
}

private TextView positionToTextView(int index) {
    switch(index){
        case 0: return textViewGMT;
        case 1: return textViewCET;
        case 2: return textViewCN;
        case 3: return textViewKR;
        case 4: return textViewIST;
    }
    return null;
}

private String bodyToTextOut(String body) {
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(body);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (jsonObject == null) return "";
    StringBuilder textOutSb = new StringBuilder();
    System.out.println("Before String");
    System.out.println("After String");
    String main = jsonObject.optString("time");
    textOutSb.append("Date: \n");
    String[] arrOfStr = main.split(" ");
    textOutSb.append(arrOfStr[0]) .append('\n')
            .append(" \n")
            .append("Time:\n")
            .append(arrOfStr[1]).append('\n');
    String desc = jsonObject.optString("timezone");
    Log.i("***main: ", main);
    Log.i("***description: ", desc);
    textOutSb.append(" \n")
            .append(desc)
            .append("\n\n");
    System.out.println("TEXTOUT" + textOutSb.toString());
    return textOutSb.toString();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    for (Call call: calls) {
        call.cancel();
    }
}

别忘了添加对okhttp的依赖以进行build.grade:

implementation 'com.squareup.okhttp3:okhttp:3.12.0'

暂无
暂无

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

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