天天看點

HttpUrlConnection和HttpClient的使用(doGet( )、doPost( )方法)伺服器中内容HttpUrlConnectionHttpClientGet方法Android中volley asyncHttp xutils

  • 伺服器中内容
  • HttpUrlConnection
    • doGet方法
      • 伺服器中的内容
    • doPost方法
  • HttpClient
  • Get方法
    • 伺服器中連接配接資料庫對使用者名和密碼進行檢查單獨寫成一個類寫在伺服器的src下
    • doPost 方法
  • Android中volley asyncHttp xutils

伺服器中内容

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();
                    //設定速去資料逾時時間
                    httpConnect.setReadTimeout();
                    //設定接收的資料類型
                    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();
                    //設定速去資料逾時時間
                    httpConnect.setReadTimeout();
                    //設定接收的資料類型
                    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(, 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(, str);
            ResultSet set = state.executeQuery();
            set.last(); //and user_word=?
            int num = set.getRow();
            if (num == ) {
                String password=name+" and user_word=?";
                PreparedStatement state1 = conn.prepareStatement("select * from user where user_name=? and user_word=?");
                state1.setString(, str);
                state1.setString(, pass);
                ResultSet set1 = state1.executeQuery();
                set1.last(); //and user_word=?
                int num1 = set.getRow();
                if (num1 == ) {
                    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(, 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);進行格式轉換,因為在資料傳輸時已經定義過了格式轉換類型

Android中volley asyncHttp xutils