android网络请求之 HttpURLConnection

简单的用一个例子;

1搭建个简单的服务器 

eclipse新建一个web项目 新建一个jsp文件

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%System.out.print("请求...."); %>
头:<%=request.getMethod() %>
姓名:<%=request.getParameter("name") %>
年龄:<%=request.getParameter("age") %>
</body>
</html>

 就是这么简单

2.客户端 先看看 HttpURLConnection  get请求

 final ProgressDialog progressDialog = ProgressDialog.show(this, null, "正在请求中....");
        new Thread() {
            @Override
            public void run() {
                super.run();
                String path = "http://192.168.1.5:8080/20190313/NewFile.jsp" + "?name=wf&age=14";
                try {
                    URL url = new URL(path); //包含请求路径的构造方法
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //得到连接对象
                    connection.setRequestMethod("GET"); //请求方式
                    connection.setConnectTimeout(5000); //设置连接超时
                    connection.setReadTimeout(5000); //读取超时
                    connection.connect(); //连接服务器
                    int response = connection.getResponseCode();  //服务器返回的结果码
                    if (response == 200) {
                        InputStream is = connection.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len = -1;
                        //将得到的io流转换成字符串
                        ByteArrayOutputStream bs = new ByteArrayOutputStream();
                        while ((len = is.read(bytes)) != -1) {
                            bs.write(bytes, 0, len);
                        }
                        final String reult = bs.toString();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText(reult);
                                progressDialog.dismiss();
                            }
                        });
                        is.close();  //关闭流 (偷懒)
                        bs.close();
                    }
                    connection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
        }.start();

get请求就是这么简单

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值