How to add AsyncTask in an HttpURLConnection?

后端 未结 3 1490
我寻月下人不归
我寻月下人不归 2020-12-11 09:08

I\'m establishing a server connection, my problem is that I need to put an AsyncTask on my code, because its not working in sdk version 10 up. I do

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 10:05

    private class ConnectionTask extends AsyncTask{
        @Override
        protected byte[] doInBackground(String... urls) {
                try {
        aURL = new URL(
                urls[0]);
    
        /* Open a connection to that URL. */
        final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();
    
        /* Define InputStreams to read from the URLConnection. */
        InputStream aInputStream = aHttpURLConnection.getInputStream();
        BufferedInputStream aBufferedInputStream = new BufferedInputStream(
                aInputStream);
    
        /* Read bytes to the Buffer until there is nothing more to read(-1) */
        ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = aBufferedInputStream.read()) != -1) {
            aByteArrayBuffer.append((byte) current);
        }
    
    
        /* Convert the Bytes read to a String. */
        aString = new String(aByteArrayBuffer.toByteArray());               } catch (IOException e) {
                    Log.d(TAG, e.toString());
                }
            return aString;
        }
    
        @Override
        protected void onPostExecute(String result) {
                   // result is what you got from your connection
    aTextView.setText(result);
    
        }
    
    }
    

    How to call it:

                            ConnectionTask task = new ConnectionTask();
                            String[] params = new String[2];
                            params[0] = url;
                            params[1] = somethingelseifneeded;
                            task.execute(params);
    

提交回复
热议问题