Android-非常棒的HTTP通讯总结

这里有一个非常棒的http通讯的总结,我看了以后茅塞顿开。
先贴代码:

public class Activity1 extends Activity {

    private final String DEBUG_TAG = "System.out";

    private TextView mTextView;
    private Button mButton;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }

    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            refresh();
        }
    }

    private void refresh() {
        String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
        // URL可以加参数
        // String httpUrl =
        // "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
        String resultData = "";
        URL url = null;
        try {
            // 创建一个URL对象
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            Log.d(DEBUG_TAG, "create URL Exception");
        }
        // 声明HttpURLConnection对象
        HttpURLConnection urlConn = null;
        // 声明InputStreamReader对象
        InputStreamReader in = null;
        // 声明BufferedReader对象
        BufferedReader buffer = null;
        String inputLine = null;
        if (url != null) {
            try {
                // 使用HttpURLConnection打开连接
                urlConn = (HttpURLConnection) url.openConnection();
                // 得到读取的内容(流)
                in = new InputStreamReader(urlConn.getInputStream());
                // 创建BufferReader对象,输出时候用到
                buffer = new BufferedReader(in);
                // 使用循环来读取数据
                while ((inputLine = buffer.readLine()) != null) {
                    // 在每一行后面加上换行
                    resultData += inputLine + "\n";
                }
                // 设置显示取的的内容
                if (resultData != null && !resultData.equals("")) {
                    mTextView.setText(resultData);
                } else {
                    mTextView.setText("读取的内容为空");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭InputStreamReader
                    in.close();
                    // 关闭URL连接
                    urlConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.d(DEBUG_TAG, "URL is NULL");
        }
    }
}

第二种方式:

public class Activity2 extends Activity {

    private final String DEBUG_TAG = "System.out";

    private TextView mTextView;
    private Button mButton;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }

    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            refresh();
        }
    }

    private void refresh() {
        String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
        String resultData = "";
        URL url = null;
        try {
            // 创建一个URL对象
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            Log.d(DEBUG_TAG, "create URL Exception");
        }
        // 声明HttpURLConnection对象
        HttpURLConnection urlConn = null;
        // 声明InputStreamReader对象
        InputStreamReader in = null;
        // 声明BufferedReader对象
        BufferedReader buffer = null;
        String inputLine = null;
        // 声明DataOutputStream流
        DataOutputStream out = null;
        if (url != null) {
            try {
                // 使用HttpURLConnection打开连接
                urlConn = (HttpURLConnection) url.openConnection();
                // 因为这个是POST请求所以要设置为true
                urlConn.setDoInput(true);
                urlConn.setDoOutput(true);
                // 设置POST方式
                urlConn.setRequestMethod("POST");
                // POST请求不能设置缓存
                urlConn.setUseCaches(false);
                urlConn.setInstanceFollowRedirects(false);
                // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
                urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成
                // 要注意的是connectio.getOutputStream会隐含的进行connect
                urlConn.connect();
                // DataOutputStream流
                out = new DataOutputStream(urlConn.getOutputStream());
                String content = "par=" + URLEncoder.encode("abcdefg", "gb2312");
                // 将要上传的内容写入流中
                out.writeBytes(content);
                // 得到读取的内容(流)
                in = new InputStreamReader(urlConn.getInputStream());
                // 创建BufferReader对象,输出时候用到
                buffer = new BufferedReader(in);
                // 使用循环来读取数据
                while ((inputLine = buffer.readLine()) != null) {
                    // 在每一行后面加上换行
                    resultData += inputLine + "\n";
                }
                // 设置显示取的的内容
                if (resultData != null && !resultData.equals("")) {
                    mTextView.setText(resultData);
                } else {
                    mTextView.setText("读取的内容为空");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 刷新DataOutputStream流
                    out.flush();
                    // 关闭DataOutputStream流
                    out.close();
                    // 关闭InputStreamReader
                    in.close();
                    // 关闭URL连接
                    urlConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.d(DEBUG_TAG, "URL is NULL");
        }
    }
}

第三种方式

public class Activity3 extends Activity{
    private TextView mTextView;
    private Button mButton;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }

    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";
            // HttpGet连接对象
            HttpGet httpRequest = new HttpGet(httpUrl);
            try {
                // 取的HttpClient对象
                HttpClient httpclient = new DefaultHttpClient();
                // 请求HttpClient,取的HttpResponse
                HttpResponse httpResponse = httpclient.execute(httpRequest);
                // 请求成功
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 取的返回的字符串
                    String strResult = EntityUtils.toString(httpResponse.getEntity());
                    // 这个返回值可能会在行尾出现小方格
                    // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
                    String strsResult = strResult.replace("\r", "");
                    mTextView.setText(strsResult);
                } else {
                    mTextView.setText("请求错误");
                }
            } catch (ClientProtocolException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (IOException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (Exception e) {
                mTextView.setText(e.getMessage().toString());
            }
        }
    }
}

第四种方式

public class Activity4 extends Activity{
    private TextView mTextView;
    private Button mButton;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }

    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View arg0) {
            String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
            // 创建HttpPost连接对象
            HttpPost httpRequest = new HttpPost(httpUrl);
            // 使用NameValuePair来保存要传递的Post参数
            List params = new ArrayList();
            // 添加要传递的参数
            params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
            try {
                // 设置字符集
                HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
                // 请求httpRequest
                httpRequest.setEntity(httpentity);
                // 取的默认的HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // 取的HttpResponse
                HttpResponse httpResponse = httpclient.execute(httpRequest);
                // HttpStatus.SC_OK表示连接成功
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 取的返回的字符串
                    String strResult = EntityUtils.toString(httpResponse.getEntity());
                    // 这个返回值可能会在行尾出现小方格
                    // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
                    String strsResult = strResult.replace("\r", "");
                    mTextView.setText(strsResult);
                } else {
                    mTextView.setText("请求错误");
                }
            } catch (ClientProtocolException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (IOException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (Exception e) {
                mTextView.setText(e.getMessage().toString());
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值