如何添加的AsyncTask在HttpURLConnection的? [英] How to add AsyncTask in an HttpURLConnection?

查看:146
本文介绍了如何添加的AsyncTask在HttpURLConnection的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器建立连接时,我的问题是,我需要把的AsyncTask 我的code,因为它不是在SDK版本工作 10 起来。我不想使用 StrictMode.ThreadPolicy

 公共类TestConnection延伸活动{@覆盖
公共无效的onCreate(捆绑cbundle){
    super.onCreate(cbundle);    ConnectivityManager aConnectivityManager =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    的NetworkInfo aNetworkInfo = aConnectivityManager.getActiveNetworkInfo();
    如果(aNetworkInfo =空&放大器;!&放大器; aNetworkInfo.isConnected()){
        Toast.makeText(这一点,网络连接,Toast.LENGTH_LONG).show();
    }其他{
        Toast.makeText(这一点,网络连接超时,Toast.LENGTH_LONG).show();
    }
    URL aURL;
    / *将充满以后显示出来。 * /
    字符串ASTRING = NULL;    / *我们将展示我们在一个TextView读取数据。 * /
    TextView的aTextView =新的TextView(本);
    尝试{        / *定义我们想从加载数据的URL。 * /
        aURL =新的URL(
                HTTP:// URL);        / *打开到URL的连接。 * /
        最后HttpURLConnection的aHttpURLConnection =(HttpURLConnection类)aURL.openConnection();        / *定义InputStreams从URLConnection的阅读。 * /
        InputStream的aInputStream = aHttpURLConnection.getInputStream();
        的BufferedInputStream aBufferedInputStream =新的BufferedInputStream(
                aInputStream);        / *读取字节的缓冲区,直到有没有更多阅读(-1)* /
        ByteArrayBuffer aByteArrayBuffer =新ByteArrayBuffer(50);
        INT电流= 0;
        而((电流= aBufferedInputStream.read())!= - 1){
            aByteArrayBuffer.append((字节)电流);
        }
        / *读取转换为字符串的字节数。 * /
        ASTRING =新的String(aByteArrayBuffer.toByteArray());
    }赶上(例外aException){        / *在我们要显示它的任何错误。 * /
        ASTRING = aException.getMessage();
    }    / *显示GUI上的字符串。 * /
    aTextView.setText(ASTRING);
    this.setContentView(aTextView);}}


解决方案

 私有类ConnectionTask扩展的AsyncTask<弦乐,太虚,字符串> {
    @覆盖
    受保护的byte [] doInBackground(字符串的URL ...){
            尝试{
    aURL =新的URL(
            网址[0]);    / *打开到URL的连接。 * /
    最后HttpURLConnection的aHttpURLConnection =(HttpURLConnection类)aURL.openConnection();    / *定义InputStreams从URLConnection的阅读。 * /
    InputStream的aInputStream = aHttpURLConnection.getInputStream();
    的BufferedInputStream aBufferedInputStream =新的BufferedInputStream(
            aInputStream);    / *读取字节的缓冲区,直到有没有更多阅读(-1)* /
    ByteArrayBuffer aByteArrayBuffer =新ByteArrayBuffer(50);
    INT电流= 0;
    而((电流= aBufferedInputStream.read())!= - 1){
        aByteArrayBuffer.append((字节)电流);
    }
    / *读取转换为字符串的字节数。 * /
    ASTRING =新的String(aByteArrayBuffer.toByteArray()); }赶上(IOException异常五){
                Log.d(TAG,e.toString());
            }
        返回ASTRING;
    }    @覆盖
    保护无效onPostExecute(字符串结果){
               //结果是你从你的连接得到了什么
aTextView.setText(结果);    }}

如何称呼它:

  ConnectionTask任务=新ConnectionTask();
                        的String [] = PARAMS新的String [2];
                        PARAMS [0] = URL;
                        PARAMS [1] = somethingelseifneeded;
                        task.execute(PARAMS);

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 don't want to use the StrictMode.ThreadPolicy.

public class TestConnection extends Activity {

@Override
public void onCreate(Bundle cbundle) {
    super.onCreate(cbundle);

    ConnectivityManager aConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo aNetworkInfo = aConnectivityManager.getActiveNetworkInfo();
    if (aNetworkInfo != null && aNetworkInfo.isConnected()){
        Toast.makeText(this, "Internet Connected", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this, "Internet Connection Timeout", Toast.LENGTH_LONG).show();
    }


    URL aURL;
    /* Will be filled and displayed later. */
    String aString = null;

    /* We will show the data we read in a TextView. */
    TextView aTextView = new TextView(this);
    try {

        /* Define the URL we want to load data from. */
        aURL = new URL(
                "http://url");

        /* 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 (Exception aException) {

        /* On any Error we want to display it. */
        aString = aException.getMessage();
    }

    /* Show the String on the GUI. */
    aTextView.setText(aString);
    this.setContentView(aTextView);

}

}

解决方案

private class ConnectionTask extends AsyncTask<String, Void, String>{
    @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);

这篇关于如何添加的AsyncTask在HttpURLConnection的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆