HttpUrlConnection

  • 服务器中内容
  • HttpUrlConnection
    • doGet方法
      • 服务器中的内容
    • doPost方法
  • HttpClient
  • Get方法
    • 服务器中连接数据库对用户名和密码进行检查单独写成一个类写在服务器的src下
    • doPost 方法

服务器中内容

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub
        String str=request.getParameter("username");
        String pass=request.getParameter("password");
        str=Encoding.doEncoding(str);
        System.out.println(str+"");
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// Connection conn=MySql.newInstance().getConnect();
// try {
// PreparedStatement state=conn.prepareStatement("select * from user where user_name=? and user_word=?");
// state.setString(1, str);
// state.setString(2, pass);
// ResultSet set =state.executeQuery();
// set.last();
// int num=set.getRow();
// if(num==1){
// System.out.println("登录成功");
// }else{
// System.out.println("不存在用户名或密码");
// }
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
        new Check(str, pass);
        response.setHeader("Content-type","text/html;charset=UTF-8");
        response.getWriter().append("我收到了: ").append(request.getContextPath()).append(str).append(pass);
    }

HttpUrlConnection

doGet()方法

是sun公司封装成的
服务器必须开着

//一个按钮下的响应事件
String urlString="http://localhost:8080/MySeverTest/webproject?username=张三";
                try {
                    //生成url
                    URL url=new URL(urlString);
                    //打开url连接
                    URLConnection connect=url.openConnection();
                    //强制造型HttpUrlConnection
                    HttpURLConnection httpConnect= (HttpURLConnection) connect;
                    //设置请求方式
                    httpConnect.setRequestMethod("GET");
                    //设置接收的数据类型
                    httpConnect.setRequestProperty("Accept-Charset", "utf-8");
                    //设置可以接受序列化的java对象
                    httpConnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //得到返回码,成功则为200,具体查看HttpUrlConnection的api
                    int code=httpConnect.getResponseCode();
                    System.out.println("http状态码"+code);
                    if(code==HttpsURLConnection.HTTP_OK){
                        InputStream is=httpConnect.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        if(line!=null){
                            System.out.println(line);
                            line=br.readLine();

                        }
                    }

"设置连接超时和请求超时后"
    String urlString="http://localhost:8080/MySeverTest/webproject?username=张三";
                try {
                    //生成url
                    URL url=new URL(urlString);
                    //打开url连接
                    URLConnection connect=url.openConnection();
                    //强制造型HttpUrlConnection
                    HttpURLConnection httpConnect= (HttpURLConnection) connect;
                    //设置请求方式
                    httpConnect.setRequestMethod("GET");
                    //设置连接超时的时间
                    httpConnect.setConnectTimeout(3000);
                    //设置速去数据超时时间
                    httpConnect.setReadTimeout(3000);
                    //设置接收的数据类型
                    httpConnect.setRequestProperty("Accept-Charset", "utf-8");
                    //设置可以接受序列化的java对象
                    httpConnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    int code=httpConnect.getResponseCode();
                    System.out.println("http状态码"+code);
                    if(code==HttpsURLConnection.HTTP_OK){
                        InputStream is=httpConnect.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        if(line!=null){
                            System.out.println(line);
                            line=br.readLine();

                        }
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(SocketTimeoutException e){
                    System.out.println("连接超时");
                }catch(ConnectException e){
                    System.out.println("拒绝连接");
                    e.printStackTrace();
                }catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

服务器中的内容

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub
        String str=request.getParameter("username");
        str=Encoding.doEncoding(str);
        System.out.println(str+"");
        response.setHeader("Content-type","text/html;charset=UTF-8");
        response.getWriter().append("我收到了: ").append(request.getContextPath()).append(str);
    }

doPost方法

public void actionPerformed(ActionEvent arg0) {
                String urlString="http://localhost:8080/MySeverTest/webproject";
                try {
                    URL url=new URL(urlString);
                    URLConnection connect=url.openConnection();
                    //强制造型HttpUrlConnection
                    HttpURLConnection httpConnect= (HttpURLConnection) connect;
                    httpConnect.setRequestMethod("POST");
                    //设置连接超时的时间
                    httpConnect.setConnectTimeout(3000);
                    //设置速去数据超时时间
                    httpConnect.setReadTimeout(3000);
                    //设置接收的数据类型
                    httpConnect.setRequestProperty("Accept-Charset", "utf-8");
                    //设置可以接受序列化的java对象
                    httpConnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    httpConnect.setDoInput(true);//默认为true,可以不设置

                    httpConnect.setDoOutput(true);//设置客户端可以给服务器提交数据,默认为false,post方法必须设置为true
                    //post方法不允许使用缓存,必须设置为false
                    httpConnect.setUseCaches(false);
                    String params="username=zhansan";
                    httpConnect.getOutputStream().write(params.getBytes());
                    int code=httpConnect.getResponseCode();
                    System.out.println("http状态码"+code);
                    if(code==HttpsURLConnection.HTTP_OK){
                        InputStream is=httpConnect.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        if(line!=null){
                            System.out.println(line);
                            line=br.readLine();

                        }
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

HttpClient

是apache使用httpUrlConnection封装的类,需要导入包httpcomponents-client-4.5-bin.zip中的lib包

Get方法

//点击事件下的httpClient语句
String urlString="http://localhost:8080/MySeverTest/webproject?username=dukang&password=123456";
                //得到builder
                HttpClientBuilder builder=HttpClientBuilder.create();
                //设置连接超时时间
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                //生成client
                HttpClient client=builder.build();
                //设置为GET()方法
                HttpGet get=new HttpGet(urlString);
                //设置服务器接收数据后的读取方式
                get.setHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");
                try {
                //执行get方法得到服务器的返回的所有数据都在response中
                    HttpResponse response=client.execute(get);
                //得到httpClient访问服务器返回的表头,包含http的状态码
                    StatusLine statusLine=response.getStatusLine();
                    //得到状态码
                    int code=statusLine.getStatusCode();
                    //对状态码进行判断
                    if(code==HttpURLConnection.HTTP_OK);
                    //连接服务器成功的话,则得到数据的实体
                    HttpEntity entity=response.getEntity();
                    //得到数据流
                    InputStream is=entity.getContent();
                    //读数据进行读取
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String line=br.readLine();
                    if(line!=null){
                        System.out.println(line);
                        line=br.readLine();
                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
"********************连接MySql单独写成一个类**********************"
//写在服务器的src下
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/** * 使用单例模式 * 创建于数据库的连接 * 因为连接数据库需要用到驱动,所以导入包 * 这些语句都是写在服务器程序中,将mysql-jdbc.jar拷贝到服务器WEB-INF的lib目录下 * @author Administrator * */
public class MySql {
    private Connection connect;
    private static MySql manger;

    public static synchronized MySql newInstance() {
        if (manger == null) {
            manger = new MySql();
        }
        return manger;
    }

    public Connection getConnect() {
        return connect;
    }

    public MySql() {
        String driver = "com.mysql.jdbc.Driver";
        String name = "root";
        String pass = "123456";
        String uri = "jdbc:mysql://localhost:3306/clazz";
        try {
            Class.forName(driver);
            connect = DriverManager.getConnection(uri, name, pass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

服务器中连接数据库,对用户名和密码进行检查单独写成一个类,写在服务器的src下

"*******************************************************"
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/** * 用来检查数据库中是否含有某个用户名或密码 * @author Administrator * */
public class Check {
    public Check(String str, String pass) {

        Connection conn = MySql.newInstance().getConnect();
        try {
            String name="select * from user where user_name=?";
            PreparedStatement state = conn.prepareStatement(name);
            state.setString(1, str);
            ResultSet set = state.executeQuery();
            set.last(); //and user_word=?
            int num = set.getRow();
            if (num == 1) {
                String password=name+" and user_word=?";
                PreparedStatement state1 = conn.prepareStatement("select * from user where user_name=? and user_word=?");
                state1.setString(1, str);
                state1.setString(2, pass);
                ResultSet set1 = state1.executeQuery();
                set1.last(); //and user_word=?
                int num1 = set.getRow();
                if (num1 == 1) {
                    System.out.println("登录成功");
                } else {
                    System.out.println("密码错误");
                }
            } else {
                System.out.println("不存在用户名");
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

doPost( )方法

“不用”

String url="http://192.168.0.31:8080/MySeverTest/webproject";
                //建立bulider
                HttpClientBuilder builder=HttpClientBuilder.create();
                //设置连接超时时间
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                //用builder的到client对象
                HttpClient client=builder.build();
                //定义为Post连接,并建立连接
                HttpPost post=new HttpPost(url);
                //分别传递用户名和密码,用ArrayList数组传递
                NameValuePair pair=new BasicNameValuePair("username", "zh");
                NameValuePair pair1=new BasicNameValuePair("password", "123456");
                ArrayList<NameValuePair> list=new ArrayList<>();
                //将数据添加到数组中
                list.add(pair);
                list.add(pair1);
                try {
                //设置得到数据实体的编码格式
                    post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
                    //设置表头的编码及内容类型
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    //得到返回的全部内容
                    HttpResponse response=client.execute(post);
                    //得到状态码
                    int code=response.getStatusLine().getStatusCode();
                    if(code==HttpURLConnection.HTTP_OK){
                    //得到传递内容的实体
                        HttpEntity entity=response.getEntity();
                        InputStream is=entity.getContent();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        //将内容按行读出
                        String line=br.readLine();
                        if(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

在服务器中不用 str=Encoding.doEncoding(str);进行格式转换,因为在数据传输时已经定义过了格式转换类型

你可能感兴趣的:(HttpUrlConnection)