2015/8/13/客户端服务器数据库综合
来源:互联网 发布:破解平台软件下载 编辑:程序博客网 时间:2024/06/03 16:52
一个例子
服务器部分
客户端部分
服务器
package com.baidu.server;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;/** * Servlet implementation class MyServerLet */@WebServlet("/MyServerLet")public class MyServerLet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServerLet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String systemout=null; String json=request.getParameter("json"); System.out.println(json); JSONObject obj=JSONObject.fromObject(json); String type=obj.getString("type"); if (type.equals(Config.LOGIN)) { systemout=LogIn.newInstance().logIn(json); }else if(type.equals(Config.REGISTER)){ systemout=Register.newInstance().register(json); }else if(type.equals(Config.LOGOUT)){ systemout=LogOut.newInstance().logOut(json); }else if(type.equals(Config.CHANGE)){ systemout=Change.newInstance().change(json); }else if(type.equals(Config.SELECT)){ systemout=Inquire.newInstance().inquire(); } response.setHeader("Content-type", "text/html;charset=UTF-8");// 让浏览器以UTF-8编码格式解析 response.getWriter().append(systemout);// response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}package com.baidu.server;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import net.sf.json.JSONObject;public class Change { private static Change ch; private Change() { } public static synchronized Change newInstance() { if (ch == null) { ch = new Change(); } return ch; } public String change(String json) { JSONObject back = new JSONObject(); JSONObject obj = JSONObject.fromObject(json); JSONObject data = obj.getJSONObject("data"); String username = data.getString("username"); String password = data.getString("password"); String passwordChange = data.getString("passwordChange"); String passwordConfirm = data.getString("passwordConfirm"); String str = null; boolean isRight = Judge.newInstance().judgeChange(username, password, passwordChange, passwordConfirm); if (isRight) { Connection conn = SQLManger.newInstance().getConnection(); //连接数据库 try { //创建一个preparedStatement对象,从数据库中筛选username和password数据对 PreparedStatement state = conn.prepareStatement("select * from user where user_name=? and password=?"); state.setString(1, username); state.setString(2, password); ResultSet set = state.executeQuery(); set.last(); int num = set.getRow(); if (num == 1) { if (passwordChange.equals(passwordConfirm)) { String update = "update user set password='" + passwordChange + "' where user_name='" + username + "'"; state.execute(update); back.put("code", 0); back.put("message", "修改成功"); str = back.toString(); num = 0; } } else { back.put("code", 1); back.put("message", "用户名或密码错误"); str = back.toString(); } } catch (SQLException e) { e.printStackTrace(); } } else { back.put("code", 2); back.put("message", "输入用户名或密码格式不正确"); str = back.toString(); } return str; }}package com.baidu.server;public class Config { public static final String LOGIN="login"; public static final String REGISTER="register"; public static final String LOGOUT="logout"; public static final String CHANGE="change"; public static final String SELECT="select";}package com.baidu.server;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class Inquire { private static Inquire in; private Inquire() { } public static synchronized Inquire newInstance() { if (in == null) { in = new Inquire(); } return in; } public String inquire() { JSONObject back = new JSONObject(); String str = null; Connection conn = SQLManger.newInstance().getConnection(); //连接数据库 try { //创建一个preparedStatement对象,从数据库中筛选username和password数据对 PreparedStatement state = conn.prepareStatement("select * from user"); ResultSet set = state.executeQuery(); set.first(); JSONArray array=new JSONArray(); while(!set.isAfterLast()){ JSONObject item=new JSONObject(); item.put("username", set.getString("user_name")); item.put("password", set.getString("password")); array.add(item); set.next(); } back.put("code", 0); back.put("message", "查询成功"); back.put("data", array); str=back.toString(); } catch (SQLException e) { back.put("code", 1); back.put("message", "查询失败"); str=back.toString(); e.printStackTrace(); } return str; }}package com.baidu.server;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Judge { /** * 改方法用来判断输入的用户名和密码的格式是否正确 * * @param userName * 传入用户名 * @param passWord * 传入密码 * @return 如果用户名和密码输入格式正确返回true 输入格式错误则返回false */ private static Judge jud; private Judge(){ } public static synchronized Judge newInstance(){ if (jud==null) { jud=new Judge(); } return jud; } public boolean judge(String username, String password) { Pattern pUser = Pattern.compile("^\\w{2,16}"); Matcher mUser = pUser.matcher(username); boolean isUserName = mUser.matches(); Pattern pPass = Pattern.compile("^\\w{2,16}"); Matcher mPass = pPass.matcher(password); boolean isPassWord = mPass.matches(); return isPassWord && isUserName; } public boolean judgeChange(String username,String password,String passwordChange,String passwordConfirm){ Pattern pUser = Pattern.compile("^\\w{2,16}"); Matcher mUser = pUser.matcher(username); boolean isUserName = mUser.matches(); Pattern pPass = Pattern.compile("^\\w{2,16}"); Matcher mPass = pPass.matcher(password); boolean isPassWord = mPass.matches(); Pattern pPassChange = Pattern.compile("^\\w{2,16}"); Matcher mPassChange = pPassChange.matcher(passwordChange); boolean isPassWordChange = mPassChange.matches(); Pattern pPassConfirm = Pattern.compile("^\\w{2,16}"); Matcher mPassConfirm = pPassConfirm.matcher(passwordChange); boolean isPassWordConfirm = mPassConfirm.matches(); return isUserName&&isPassWord&&isPassWordChange&&isPassWordConfirm; }}package com.baidu.server;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import net.sf.json.JSONObject;public class LogIn { private static LogIn in; private LogIn() { } public static synchronized LogIn newInstance() { if (in == null) { in = new LogIn(); } return in; } public String logIn(String json) { JSONObject back = new JSONObject(); JSONObject obj = JSONObject.fromObject(json); JSONObject data = obj.getJSONObject("data"); String username = data.getString("username"); String password = data.getString("password"); String str = null; boolean isRight = Judge.newInstance().judge(username, password); if (isRight) { Connection conn = SQLManger.newInstance().getConnection(); //连接数据库 try { //创建一个preparedStatement对象,从数据库中筛选username和password数据对 PreparedStatement state = conn.prepareStatement("select * from user where user_name=? and password=?"); state.setString(1, username); state.setString(2, password); ResultSet set = state.executeQuery(); set.last(); int num = set.getRow(); if (num == 1) { back.put("code", 0); back.put("message", "登录成功"); str = back.toString(); } else { back.put("code", 1); back.put("message", "用户名或密码错误"); str = back.toString(); } } catch (SQLException e) { e.printStackTrace(); } } else { back.put("code", 2); back.put("message", "输入用户名或密码格式不正确"); str = back.toString(); } return str; }}package com.baidu.server;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import net.sf.json.JSONObject;public class LogOut { private static LogOut out; private LogOut() { } public static synchronized LogOut newInstance() { if (out == null) { out = new LogOut(); } return out; } public String logOut(String json) { JSONObject back = new JSONObject(); JSONObject obj = JSONObject.fromObject(json); JSONObject data = obj.getJSONObject("data"); String username = data.getString("username"); String password = data.getString("password"); String str = null; boolean isRight = Judge.newInstance().judge(username, password); if (isRight) { Connection conn = SQLManger.newInstance().getConnection(); //连接数据库 try { //创建一个preparedStatement对象,从数据库中筛选username和password数据对 PreparedStatement state = conn.prepareStatement("select * from user where user_name=? and password=?"); state.setString(1, username); state.setString(2, password); ResultSet set = state.executeQuery(); set.last(); int num = set.getRow(); if (num == 1) { String delete = "delete from user where user_name='" + username + "'"; state.execute(delete); back.put("code", 0); back.put("message", "注销成功"); str = back.toString(); num = 0; } else { back.put("code", 1); back.put("message", "用户名或密码错误"); str = back.toString(); } } catch (SQLException e) { e.printStackTrace(); } } else { back.put("code", 2); back.put("message", "输入用户名或密码格式不正确"); str = back.toString(); } return str; }}package com.baidu.server;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import net.sf.json.JSONObject;public class Register { private static Register reg; private Register() { } public static synchronized Register newInstance() { if (reg == null) { reg = new Register(); } return reg; } public String register(String json) { JSONObject back = new JSONObject(); JSONObject obj = JSONObject.fromObject(json); JSONObject data = obj.getJSONObject("data"); String username = data.getString("username"); String password = data.getString("password"); String str = null; boolean isRight = Judge.newInstance().judge(username, password); if (isRight) { Connection conn = SQLManger.newInstance().getConnection(); //连接数据库 try { //创建一个preparedStatement对象,从数据库中筛选username和password数据对 PreparedStatement state = conn.prepareStatement("select * from user where user_name=?"); state.setString(1, username); ResultSet set = state.executeQuery(); set.last(); int num = set.getRow(); if (num > 0) { back.put("code", 1); back.put("message", "该用户已存在"); str = back.toString(); } else { String register = "insert into user(user_name,password) values('" + username + "','" + password + "')"; state.execute(register); //执行方法找到一个与 methodName 属性同名的方法,并在目标上调用该方法 back.put("code", 0); back.put("message", "创建成功"); str = back.toString(); } } catch (SQLException e) { e.printStackTrace(); } } else { back.put("code", 2); back.put("message", "输入用户名或密码格式不正确"); str = back.toString(); } return str; }}package com.baidu.server;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class SQLManger { private Connection connection; public Connection getConnection() { return connection; } /** * 单例设计模式 */ private static SQLManger manger; public static synchronized SQLManger newInstance(){ if (manger==null) { manger=new SQLManger(); } return manger; } /*** * 该方法是用来连接指定url的数据库 * localhost可以写成别人的ip地址,这样就能连接到别人的数据库 */ private SQLManger (){ String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/clazz"; String user="root"; String password="123456"; try { Class.forName(driver); connection=DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }}
客户端
package com.baidu.client;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JTextField;import javax.swing.JPasswordField;import javax.swing.JLabel;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class MyClient extends JFrame { private JPanel contentPane; private JTextField textFieldUserName; private JPasswordField passwordFieldPass; private JPasswordField passwordFieldChange; private JPasswordField passwordFieldConfirm; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MyClient frame = new MyClient(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MyClient() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 426, 513); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textFieldUserName = new JTextField(); textFieldUserName.setBounds(122, 27, 190, 37); contentPane.add(textFieldUserName); textFieldUserName.setColumns(10); passwordFieldPass = new JPasswordField(); passwordFieldPass.setBounds(122, 91, 190, 37); contentPane.add(passwordFieldPass); JLabel label = new JLabel("用户名"); label.setBounds(23, 38, 54, 15); contentPane.add(label); JLabel label_1 = new JLabel("密码"); label_1.setBounds(23, 102, 54, 15); contentPane.add(label_1); JButton button = new JButton("登录"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String userName=textFieldUserName.getText(); char[] a=passwordFieldPass.getPassword(); String password=new String(a); ClientLogIn reg=new ClientLogIn(); reg.doPost(userName, password); } }); button.setBounds(265, 152, 93, 37); contentPane.add(button); JButton button_1 = new JButton("注册"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String userName=textFieldUserName.getText(); char[] a=passwordFieldPass.getPassword(); String password=new String(a); ClientRegister reg=new ClientRegister(); reg.doPost(userName, password); } }); button_1.setBounds(98, 152, 93, 37); contentPane.add(button_1); JButton button_2 = new JButton("注销"); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String userName=textFieldUserName.getText(); char[] a=passwordFieldPass.getPassword(); String password=new String(a); ClientLogOut reg=new ClientLogOut(); reg.doPost(userName, password); } }); button_2.setBounds(98, 216, 93, 37); contentPane.add(button_2); JButton button_3 = new JButton("改密"); button_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String userName=textFieldUserName.getText(); char[] a=passwordFieldPass.getPassword(); String password=new String(a); char[] a1=passwordFieldChange.getPassword(); String passwordChange=new String(a1); char[] a2=passwordFieldConfirm.getPassword(); String passwordConfirm=new String(a2); ClientChange clc=new ClientChange(); clc.doPost(userName, password, passwordChange, passwordConfirm); } }); button_3.setBounds(122, 379, 190, 33); contentPane.add(button_3); JButton button_4 = new JButton("退出"); button_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); button_4.setBounds(265, 216, 93, 37); contentPane.add(button_4); passwordFieldChange = new JPasswordField(); passwordFieldChange.setBounds(122, 279, 190, 37); contentPane.add(passwordFieldChange); passwordFieldConfirm = new JPasswordField(); passwordFieldConfirm.setBounds(122, 326, 190, 37); contentPane.add(passwordFieldConfirm); JLabel label_2 = new JLabel("修改密码"); label_2.setBounds(10, 290, 54, 15); contentPane.add(label_2); JLabel label_3 = new JLabel("确认密码"); label_3.setBounds(10, 337, 54, 15); contentPane.add(label_3); JButton btnNewButton = new JButton("跳转到查询界面"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EventQueue.invokeLater(new Runnable() { public void run() { try { Inquire frame = new Inquire(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }); btnNewButton.setBounds(122, 432, 190, 33); contentPane.add(btnNewButton); }}package com.baidu.client;import java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JTextField;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class Inquire extends JFrame { private JPanel contentPane; private JTextField textField; /** * Create the frame. */ public Inquire() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 218, 204); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton button = new JButton("点击查询"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ClientInquire inquire=new ClientInquire(); inquire.doPost(); } }); button.setBounds(52, 118, 107, 31); contentPane.add(button); JLabel label = new JLabel(" 输入需要查询的用户名"); label.setBounds(10, 32, 182, 15); contentPane.add(label); textField = new JTextField(); textField.setBounds(52, 67, 107, 31); contentPane.add(textField); textField.setColumns(10); }}package com.baidu.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import net.sf.json.JSONObject;public class ClientChange { /*** * 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8 * 执行post方法得到服务器的返回的所有数据都在response中 * @param userName 传入用户名 * @param passWord 传入密码 */ public void doPost(String userName,String password,String passwordChange,String passwordConfirm){ String urlString="http://localhost:8080/ThirteenAugMyServer/MyServerLet"; HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时 HttpClient client=builder.build(); //创建Client HttpPost post=new HttpPost(urlString); //设置为Post方法 JSONObject obj=new JSONObject(); obj.put("type", "change"); JSONObject data=new JSONObject(); data.put("username",userName); data.put("password", password); data.put("passwordChange", passwordChange); data.put("passwordConfirm", passwordConfirm); obj.put("data", data); NameValuePair pair=new BasicNameValuePair("json" ,obj.toString()); // ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组 params.add(pair); //添加元素 try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK) { HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}package com.baidu.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import net.sf.json.JSONObject;public class ClientInquire { /*** * 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8 * 执行post方法得到服务器的返回的所有数据都在response中 * @param userName 传入用户名 * @param passWord 传入密码 */ public void doPost(){ String urlString="http://localhost:8080/ThirteenAugMyServer/MyServerLet"; HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时 HttpClient client=builder.build(); //创建Client HttpPost post=new HttpPost(urlString); //设置为Post方法 //封装为JSON格式 JSONObject obj=new JSONObject(); obj.put("type", "select"); NameValuePair pair=new BasicNameValuePair("json" ,obj.toString()); // ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组 params.add(pair); //添加元素 try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK) { HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}package com.baidu.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import net.sf.json.JSONObject;public class ClientLogIn { /*** * 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8 * 执行post方法得到服务器的返回的所有数据都在response中 * @param userName 传入用户名 * @param passWord 传入密码 */ public void doPost(String userName,String password){ String urlString="http://localhost:8080/ThirteenAugMyServer/MyServerLet"; HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时 HttpClient client=builder.build(); //创建Client HttpPost post=new HttpPost(urlString); //设置为Post方法 //封装为JSON格式 JSONObject obj=new JSONObject(); obj.put("type", "login"); JSONObject data=new JSONObject(); data.put("username",userName); data.put("password", password); obj.put("data", data); NameValuePair pair=new BasicNameValuePair("json" ,obj.toString()); // ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组 params.add(pair); //添加元素 try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK) { HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}package com.baidu.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import net.sf.json.JSONObject;public class ClientLogOut { /*** * 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8 * 执行post方法得到服务器的返回的所有数据都在response中 * @param userName 传入用户名 * @param passWord 传入密码 */ public void doPost(String userName,String password){ String urlString="http://localhost:8080/ThirteenAugMyServer/MyServerLet"; HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时 HttpClient client=builder.build(); //创建Client HttpPost post=new HttpPost(urlString); //设置为Post方法 JSONObject obj=new JSONObject(); obj.put("type", "logout"); JSONObject data=new JSONObject(); data.put("username",userName); data.put("password", password); obj.put("data", data); NameValuePair pair=new BasicNameValuePair("json" ,obj.toString()); // ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组 params.add(pair); //添加元素 try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK) { HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}package com.baidu.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicNameValuePair;import net.sf.json.JSONObject;public class ClientRegister { /*** * 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8 * 执行post方法得到服务器的返回的所有数据都在response中 * @param userName 传入用户名 * @param passWord 传入密码 */ public void doPost(String userName,String password){ String urlString="http://localhost:8080/ThirteenAugMyServer/MyServerLet"; HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时 HttpClient client=builder.build(); //创建Client HttpPost post=new HttpPost(urlString); //设置为Post方法 JSONObject obj=new JSONObject(); obj.put("type", "register"); JSONObject data=new JSONObject(); data.put("username",userName); data.put("password", password); obj.put("data", data); NameValuePair pair=new BasicNameValuePair("json" ,obj.toString()); // ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组 params.add(pair); //添加元素 try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型 post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8 HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中 int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码 if (code==HttpURLConnection.HTTP_OK) { HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
0 0
- 2015/8/13/客户端服务器数据库综合
- mysql数据库客户端和mysql数据库服务器
- PHP本地服务器localhost与数据库MySQL的综合运用
- ORACLE数据库客户端连接访问服务器
- ORACLE客户端与数据库服务器连接
- 嵌入式数据库 服务器-客户端网络访问实现
- 不安装Oracle客户端访问服务器数据库
- oracle数据库字符集、服务器字符集、客户端字符集
- C# 客户端 在 服务器获取数据库图片
- 解决客户端无法连接服务器数据库SQL2000
- 登录界面,数据库,服务器,客户端的连接
- 新闻客户端综合案例
- select服务器编程综合
- poll服务器编程综合
- VC++套接字、数据库、文件读写综合应用-客户端读取文件套接字接收服务端写入数据库
- 对java从数据库和服务器硬盘读出并写入的综合
- 【服务器+手机端项目】Android+Servlet+JSON综合案例之数据库设计【一】
- PHP实现客户端将CSV文件导入服务器数据库中
- java输出获取英文字母
- 一个应届毕业生的求职回忆录(留给自己)
- NetIQChariot5.4网络带宽测试工具使用的代价!!!
- 1.BUG单
- tableview 索引条问题
- 2015/8/13/客户端服务器数据库综合
- SpringMVC在IE下出现无法启动应用程序的错误!
- CoreImage 中的模糊滤镜
- 最优间隔分类、原始/对偶问题、SVM对偶—斯坦福ML公开课笔记7
- leetcode Minimum&&Max Depth of Binary Tree 求树的最小&&最大深度
- How browsers work
- MySql 定时任务 Event Scheduler
- DetachedCriteria离线查询示例
- 《Unity初试面试评级标准初稿》请拍砖。。。