网络编程url,httpurlconnection,post,get

URL只能单向获取数据;url代表统一资源定位符,是指向网络访问资源的指针;
格式:1.网络协议的类型 2.主机IP加端口 3.服务器上的具体资源路径

public class TestURL3 {
    //单向读取服务器文件,并保存在本地
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/myserver/index.html");
            InputStream input = url.openStream();

            File file = new File(url.getFile());

            String filename = file.getName();

            System.out.println(filename);

            fos = new FileOutputStream("f:" + File.separator + filename);

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = input.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            System.out.println("下载完成");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

URLConnection 抽象类的子类HttpURLConnection代表应用程序和URL之间的通讯链接,用于读取URL应用文件。可以双向访问资源

get和post发送数据区别
get和post请求区别
1.get同过地址栏重写键值对的方式追加在地址栏后面提交数据,post是以字节流方式提交;
2.get一次传输不能超过2k,post没有限制;
3.get信息会暴露,存在安全隐患。

post解析

public class Post {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            //提交数据
            URL url = new URL("http://localhost:8080/mywebtest/DoLogin");
            //建立连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");//设置服务器提交方式为POST方式

            connection.setDoOutput(true);//是否允许对外输出,默认是true,写

            //提交完毕,返回json

            connection.setDoInput(true);//运行读

            connection.setConnectTimeout(5000);//设置超时时间,5秒内都会一直发送链接尝试

            //拼接"username=1&password=1"

            Map<String, String> params = new HashMap<>();

            params.put("username", "admin");
            params.put("password", "1");
            StringBuilder builder =  new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.append(entry.getKey());
                builder.append("=");
                builder.append(entry.getValue());
                builder.append("&");

            }
            String strparams = builder.deleteCharAt(builder.length()-1).toString();//删除结尾的&
            //获得链接对象关联的输出流,向服务器端写数据
//          System.out.println(strparams);
            byte[] d= strparams.getBytes();//获取strparams长度


            //设置上传流属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//固定的
            connection.setRequestProperty("Content-Length", String.valueOf(d.length));//字符串的字节长度

            //写到服务器端
            OutputStream os = connection.getOutputStream();//指向serverlet(Dologin)
            os.write(d);
            os.flush();
            os.close();//数据提交完毕

            //判断响应结果码

            int statusCode = connection.getResponseCode();//获得相应状态码是不是200

            if(statusCode == 200){
                InputStream is= connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = br.readLine();
                System.out.println("JSONObject:"+line);

                JSONObject jo = JSONObject.fromObject(line);

                String result = jo.getString("result");

                if(result.equals("ok")){
                    System.out.println("登陆成功");
                }else{
                    System.out.println("登陆失败");
                }


            }else{
                System.out.println("statusCode:"+statusCode);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

get解析

public class Get {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            //提交数据
            URL url = new URL("http://localhost:8080/mywebtest/DoLogin?username=admin&password=1");
            //建立连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");//设置服务器提交方式为get方式

            connection.setDoOutput(true);//是否允许对外输出,默认是true,写

            //提交完毕,返回json

            connection.setDoInput(true);//运行读

            connection.setConnectTimeout(5000);//设置超时时间,5秒内都会一直发送链接尝试

            int statusCode = connection.getResponseCode();//获得相应状态码是不是200

            if(statusCode == 200){
                InputStream is= connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = br.readLine();

                JSONObject jo = JSONObject.fromObject(line);

                String result = jo.getString("result");

                if(result.equals("ok")){
                    System.out.println("登陆成功");
                }else{
                    System.out.println("登陆失败");
                }


            }else{
                System.out.println("statusCode:"+statusCode);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值