使用HttpUrlConnection的GET方式返回响应信息

1 . http://localhost:8080/Day28_03/LoginServlet?useName=zhangsan&pwd=123这个链接是登陆之后会先显示登陆成功或者失败信息
2 . 其实和上文从网上下载数据是一个道理,只不过响应的信息不同,这个响应的信息是登陆成功提示的信息,但是从网上下载数据响应的是需要下载的数据.
3 . 步骤和上文基本一样

package com.qf.demo5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
// get方式  返回相应信息
public class Test2 {

    public static void main(String[] args) {
        // 1 URL 
        InputStreamReader reader =null;
        BufferedReader reader2 =null;
        try {
            URL url = new URL("http://localhost:8080/Day28_03/LoginServlet?useName=zhangsan&pwd=123");

            // 2 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3 设定请求方式
            connection.setRequestMethod("GET");
            // 4 建立连接
            connection.connect();
            // 5 
            if(connection.getResponseCode() == 200){
                // 读取响应内容
                 reader = new InputStreamReader(connection.getInputStream(),"utf-8"); 
                 reader2 = new BufferedReader(reader);
                String string = reader2.readLine();
                System.out.println("服务端响应的结果"+string);
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(reader2!=null){
                try {
                    reader2.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值