网络访问GET,POST两种方式的基本步骤

来源:互联网 发布:药智数据网 编辑:程序博客网 时间:2024/06/04 19:48
400  未连接
500  传递数据有问题
200  正确响应


一、网络访问GET方法的基本步骤:

1>定义一个服务器的地址
    String PATH = "http://192.168.1.76:8080/loginServer/LoginServlet?username=" + URLEncoder.encode(username) +"&password=" + password ;
2>创建一个URL对象,把服务器地址放进去
    URL url = new URL(PATH);
3>创建一个HttpURLConnection对象
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
4>配置参数
    //设置传输方式
    connection.setRequestMethod("GET");

    //设置连接超时
    connection.setConnectTimeout(TIME_OUT);
    //设置读取超时
    
    connection.setReadTimeout(TIME_OUT);
5>打开链接
    connection.connect();
6>获取状态码
    int responseCode = connection.getResponseCode();
7>通过传来的状态码进行判断 200表示连接成功
    if (200==responseCode) {

    //获取返回值
 输入流                        
    InputStream inputStream = connection.getInputStream();
                        
    //将字节流输入流转换为字符串
                        
    String data = StreamUtils.inputSteam2String(inputStream);
                        
                }

                
                

二、网络访问POST方法的基本步骤:

1>定义一个服务器的地址
    String PATH = "http://192.168.0.100:8080/loginServer/LoginServlet"
2>创建一个URL对象,把服务器地址放进去
    URL url = new URL(PATH);
3>创建一个HttpURLConnection对象
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
4>配置参数
    //设置传输方式
    connection.setRequestMethod("POST");
    //设置该参数,才能以流的形式提交数据 150. * 需要将要提交的数据转换为字节输出流
    connection.setDoInput(true);

    //设置连接超时
    connection.setConnectTimeout(TIME_OUT);
    //设置读取超时
    
    connection.setReadTimeout(TIME_OUT);
5>将提交的参数进行URL编码
                    
    String param = "username=" + URLEncoder.encode(username) +"&password=" + password ;
        
6>设置请求体的长度
                    
    connection.setRequestProperty("Content-Length", param.length()+"");
                    
7>设置请求属性,相当于封装http的请求头参数
                    
    connection.setRequestProperty("Context-Type", "application/x-www-form-urlencoded");
8>打开链接
    connection.connect();
9>获取输出流
    OutputStream os = connection.getOutputStream();
10>通过输出流把数据交出去并关闭
    os.write(param.getBytes());
    //关闭流
    os.close();
11>获取状态码
    int responseCode = connection.getResponseCode();

12>通过传来的状态码进行判断 200表示连接成功
    if (200==responseCode) {

    //获取返回值
 输入流                        
    InputStream inputStream = connection.getInputStream();
                        
    //将字节流输入流转换为字符串
                        
    String data = StreamUtils.inputSteam2String(inputStream);
                        
                }
原创粉丝点击