Android中的网络请求之HttpURLConnection

来源:互联网 发布:淘宝胶带囤货什么意思 编辑:程序博客网 时间:2024/05/18 03:50

HttpURLConnection简介

HttpURLConnection是URLConnection的子类,每个HttpURLConnection 实例都可用于生成单个请求

HttpURLConnection请求的两种方式及步骤

网络请求数据步骤如下(Get请求)
1.根据url创建URL对象
2.打开连接,获得HttpUrlConnction对象
3.获取响应码(getResponseCode)
4.得到结果的输入流(getInputStream)

网络请求数据步骤如下(post请求)
1.根据url创建URL对象
2.打开连接,获得HttpUrlConnction对象
3.设置请求方式为post
4.设置要向服务器写入数据(conn.setDoOutput(true))
5获得输出流将参数信息写进去
6.获取响应码(getResponseCode)
7.得到响应输入流(getInputStream)

如下代码实现使用HttpUrlConnction的post的方法从http://v.juhe.cn/toutiao/index接口中获取数据并解析输出,显示在listview控件上

/**
* HttpURLConnection 执行post请求的案例
* @author e531
*
*/
public class MainActivity extends Activity {

private Handler myHandler=new Handler(){    public void handleMessage(android.os.Message msg) {        List<News> lists=(List<News>)msg.obj;        //设置适配器,显示        //.......    };};@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);}public void requestNews(View v){    new Thread(){        public void run() {            //注意:进行post请求时,请求的地址是不包含 参数信息的(?...)            String path="http://v.juhe.cn/toutiao/index";            try {                //1.创建一个URL                URL url=new URL(path);                //2.打开连接                HttpURLConnection openConnection =(HttpURLConnection) url.openConnection();                //3.设置一些设置                openConnection.setRequestMethod("POST");//post必须要大写                openConnection.setReadTimeout(3000);                openConnection.setConnectTimeout(3000);                //4.设置输出参数                openConnection.setDoOutput(true);                //请求的参数                String params="type=keji&key=c4479ad58f41e7f78a8fa073d0b1f1b5";                openConnection.getOutputStream().write(params.getBytes());                //5.得到响应码                int code=openConnection.getResponseCode();                if(code==200){                    //6.得到结果                    InputStream inputStream = openConnection.getInputStream();                    //结果                    String content=streamToString(inputStream);                    Log.d("zzz", content);                    //进行解析                    Gson gs=new Gson();                    Result result=gs.fromJson(content, Result.class);                    Log.d("zzz", result.toString());                    //新闻列表数据                    List<News> datas = result.getResult().getData();            //发送消息                    Message msg=Message.obtain();                    msg.obj=datas;                    myHandler.sendMessage(msg);    }} catch (MalformedURLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }};    }.start();}/** * 将字节流信息的内容读取出来 * @param is * @return */public String streamToString(InputStream is){    StringBuilder builder=new StringBuilder();    BufferedReader reader=new BufferedReader(new InputStreamReader(is));    String con;    try {        while((con=reader.readLine())!=null){            builder.append(con);        }        reader.close();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    return builder.toString();

}

}

阅读全文
0 0
原创粉丝点击