android学习笔记 之 HttpUrlconnection的使用



在Android上发送HTTP请求的常用的有两种方式,HttpURLConnection和HttpClient,本次学习HttpURLConnection的使用

 1. new 一个URL对象,并传入网络地址,然后调用openConnection()方法,如下

                 URL url = new URL("http://www.baidu.com");
		connection=(HttpURLConnection) url.openConnection();

2.得到HttpURLConnection的实例后,可以设置HTTP请求的方法。常用的有GET和POST,GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器。

	       connection.setRequestMethod("GET");
3.除此之外还可以进行一些其它设置,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。如下所示:

               connection.setConnectTimeout(8000);
	       connection.setReadTimeout(8000);
4.然后调用getInputStream()方法获取服务器返回的输入流,并对输入流进行读取。

               InputStream in = connection.getInputStream();
	        //下面对获取的输入流进行读取
	      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
5.最后关闭HTTP链接

	   connection.disconnect();
示例代码下载地址

6.例子

/**
 * Created by  /6/8.
 * 网络请求接口
 */
public interface HttpCallbackListener {
    void onFinish(String respone);
    void onErroe(Exception e);
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by  on 2017/6/8.
 * 网络工具
 */

public class HttpUtil {
    public static String sendHttpRequest(String address){
        HttpURLConnection connection=null;
        try {
            URL url = new URL(address);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder respone = new StringBuilder();
            String  line ;
            while((line=reader.readLine())!=null){
                respone.append(line);
            }
            return respone.toString();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
        }

    }


    public static void sendHttpRequest(final String address,
                                       final HttpCallbackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection =null;


                try {
                    URL url = new URL(address);
                    httpURLConnection= (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(8000);
                    httpURLConnection.setReadTimeout(8000);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line=bufferedReader.readLine())!=null){
                        response.append(line);

                    }
                    if (listener !=null){

//                     回调onfinish
                        listener.onFinish(response.toString());
                    }

                } catch (Exception e) {

                    e.printStackTrace();
                    if(listener !=null){
//                        回调 error 方法
                    }
                }finally {
                    if(httpURLConnection !=null){
                        httpURLConnection.disconnect();
                    }
                }


            }
        }).start();
    }
}


使用


        String address="http://www.baidu.com";
//        String response = HttpUtil.sendHttpRequest(address);

        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(final String respone) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplication(),respone,Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onErroe(Exception e) {

            }
        });




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值