HttpClient中的doGet和doPost实例
将从View中得到数据提交到服务器,服务器再连接数据库,在进行分析,返回相应的信息到客户端View。可以分为三部分,前端view客户端界面,服务器,后台数据库。
#
这里我们假定客户端界面可以有注册,登录、查询操作
创建一个Jframe,在按钮事件里添加以下代码(注册)
String url="http://localhost:8080/MyServersTest/MyTestServerlet";
String useName=textAreaUserName.getText();
String password=textAreaPassword.getText();
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost httpPost=new HttpPost(url);
JSONObject jsonObject=new JSONObject();
jsonObject.put("type", "regiter");
JSONObject data=new JSONObject();
data.put("userName",useName);
data.put("password",password);
jsonObject.put("data", data);
NameValuePair pair=new BasicNameValuePair("json", jsonObject.toString());
ArrayList< NameValuePair> params=new ArrayList<>();
params.add(pair);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
httpPost.setHeader("content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response=client.execute(httpPost);
int code=response.getStatusLine().getStatusCode();
if (code==200) {
HttpEntity entity=response.getEntity();
BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
String line=br.readLine();
try {
MyDialog dialog = new MyDialog(line);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
while (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();
}
以下是登录时的代码,和注册一样
String url="http://localhost:8080/MyServersTest/MyTestServerlet";
String useName=textAreaName.getText();
String password=textArea_1Password.getText();
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost httpPost=new HttpPost(url);
JSONObject jsonObject=new JSONObject();
jsonObject.put("type", "login");
JSONObject data=new JSONObject();
data.put("userName",useName);
data.put("password",password);
jsonObject.put("data", data);
NameValuePair pair=new BasicNameValuePair("json", jsonObject.toString());
ArrayList< NameValuePair> params=new ArrayList<>();
params.add(pair);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
httpPost.setHeader("content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response=client.execute(httpPost);
int code=response.getStatusLine().getStatusCode();
if (code==200) {
HttpEntity entity=response.getEntity();
BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
String line=br.readLine();
try {
System.out.println(line);
MyDialog dialog = new MyDialog(line);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
while (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();
}
查询
String url="http://localhost:8080/MyServersTest/MyTestServerlet";
String useName=textAreaName.getText();
String password=textAreaPassword.getText();
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost httpPost=new HttpPost(url);
JSONObject jsonObject=new JSONObject();
jsonObject.put("type", "select");
JSONObject data=new JSONObject();
data.put("userName",useName);
data.put("password",password);
jsonObject.put("data", data);
NameValuePair pair=new BasicNameValuePair("json", jsonObject.toString());
ArrayList< NameValuePair> params=new ArrayList<>();
params.add(pair);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
httpPost.setHeader("content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response=client.execute(httpPost);
int code=response.getStatusLine().getStatusCode();
if (code==200) {
HttpEntity entity=response.getEntity();
BufferedReader br=new BufferedReader(new InputStreamReader(entity.getContent()));
String line=br.readLine();
JSONObject object=JSONObject.fromObject(line);
String datas=object.getString("data");
JSONObject obdata=JSONObject.fromObject(datas);
String name=obdata.getString("userName");
String passwords=obdata.getString("password");
String num=object.getString("num");
String code1=object.getString("code");
try {
System.out.println(line);
if (num.equals("0")) {
MyDialog dialog = new MyDialog(code1+" 用户名:"+name+" 密码:"+passwords);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}else{
MyDialog dialog = new MyDialog(code1);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
} catch (Exception e1) {
e1.printStackTrace();
}
while (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();
}
以上代码中添加了一个对话框,代码如下:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
public MyDialog(String line) {
setBounds(100, 100, 250, 152);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPanel.add(new JLabel(line));
getContentPane().add(contentPanel, BorderLayout.CENTER);
}
}
服务器端的代码如下:
String json=request.getParameter("json");
String s="";
System.out.println("得到的数据"+json);
JSONObject jsonObject=JSONObject.fromObject(json);
// if (jsonObject!=null) {
String type=jsonObject.getString("type");
String dataString=jsonObject.getString("data");
JSONObject data=jsonObject.fromObject(dataString);
String userName=data.getString("userName");
String password=data.getString("password");
userName=Encoding.doEncoding(userName);
Connection connection=SQLManager.newInstabce().getConn();
Statement statement=SQLManager.newInstabce().getState();
if (type.equals("regiter")) {
try {
if (!connection.isClosed()) {
String select= "select * from user where name='"+userName+"'";
ResultSet set= statement.executeQuery(select);
set.last();
System.out.println(set.last());
int num=set.getRow();
System.out.println("num:"+num);
if (num>0) {
s="该用户已注册";
}else{
String insert="insert into user(name,password)values('" + userName + "','" + password
+ "')";
statement.execute(insert);
s="注册成功!";
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(type.equals("login")){
try {
if (!connection.isClosed()) {
String select= "select * from user where name='"+userName+"'and password='"+password+"'";
ResultSet set= statement.executeQuery(select);
set.last();
System.out.println(set.last());
int num=set.getRow();
System.out.println("num:"+num);
if (num>0) {
s="登录成功!";
}else{
s="登录失败!";
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
if (!connection.isClosed()) {
String select= "select * from user where name='"+userName+"'and password='"+password+"'";
ResultSet set= statement.executeQuery(select);
set.last();
System.out.println(set.last());
int num=set.getRow();
System.out.println("num:"+num);
String respone=null;
if (num>0) {
respone="查询成功";
jsonObject.put("code", respone);
jsonObject.put("num", 0);
s=jsonObject.toString();
}else{
respone="查询失败!";
jsonObject.put("code", respone);
jsonObject.put("num", 1);
s=jsonObject.toString();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().append(s);