客户端的:
doGet:直接连接在url后边,是显式的。
doPost:比get安全,是隐式的。
HttpUrlConnection 是sun公司封装成的网络连接
HttpClient 是apache使用httpUrlConnection封装的类,特点:较为简单
Android中放弃了这两种,重新封装为volley, asycllttp ,xutils
小知识:
1.用doGet方法就调用服务器端的doGet方法,
用doPost:方法就调用服务器端的doPost方法,可以在服务器的doPost方法中调用doGet方法。
2.测试时:先运行服务器,然后在客户端,用doGet或doPost或HTTPClient(需要导入jar包,到HTTPClient官网中下载)等方法来与服务器里连接并传输数据。
服务器端:
//服务器端的doGet方法中:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = null;
//获取传来的数据
String name = request.getParameter("name");
name = Ecoding.doEncoding(name); //下面有转码代码
System.out.println(name);
String password = request.getParameter("password");
password = Ecoding.doEncoding(password);
System.out.println(password);
//判断数据库是否有用户
boolean isExist = SQLOperation.Intance().IsExist(name, password);
if(isExist){
s = "登录成功!";
}else{
s = "登录失败!";
}
//返回时,加一句,让浏览器以UTF-8编码格式解析:(注:此时浏览器编码格式必须是UTF-8格式)
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().append(s);
}
//转码类
public class Ecoding {
public static String doEncoding(String string){//此方法用于将浏览器的数据编码转成UTF-8
try {
byte[] array = string.getBytes("ISO-8859-1");
string = new String(array,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
}
步骤:
1.生成URL:
new URL,注意链接后接传输的数据。
2.打开url连接,并强转为HTTPURLConnection格式:
url.openConnection()方法
3.设置请求方式:
setRequestMethod(“GET或者POST”);
4.设置编码格式,可接受的数据类型(固定)
httpConnection.setRequestProperty(“Accept-Charset”, “utf-8”);
5.设置可以接受的序列化的java对象(固定)
httpConnection.setRequestProperty(“Content-type”, “application/x-www-form-urlencoded”);
可以选择的用法:
1>连接超时:setConnectTimeout()方法, —–>ConnectException e异常(一般是连接服务器时超时,产生这个异常)
等待返回时间超时: setReadTimeout()方法 —–>SocketTimeoutException e异常(一般是等待服务器返回值超时,产生这个异常。)
2>获取服务器返回的数据:httpConnection.getInputStream();
doGet范例:
/*功能:利用doGet方法与服务器传输数据
*/
try {
//1.生成URL
URL url = new URL("http://localhost:8080/MyTest/MySverlet?name=zhangsan&password=123");
//2.打开url连接
URLConnection connect =(URLConnection) url.openConnection();
//3.强制造型成httpUrlConnection
HttpURLConnection httpConnection = (HttpURLConnection) connect;
//4.设置请求方式
httpConnection.setRequestMethod("GET");
//5.设置编码格式,可接受的数据类型(固定)
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
//6.设置可以接受的序列化的java对象(固定)
httpConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//8.设置连接超时
httpConnection.setConnectTimeout(3000);//连接chaoshi
httpConnection.setReadTimeout(3000); //等待返回时间超时
//7.通过状态码判断
int code = httpConnection.getResponseCode();
System.out.println(code);
if(code==HttpURLConnection.HTTP_OK){
//如果正常获得,则获取值
InputStream is= httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch(SocketTimeoutException e1){
System.out.println("网络连接出问题!");
} catch(ConnectException e1){
System.out.println("服务器未开!");
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
9.接收数据与doGet相同:(通过状态吗判断)接收服务器返回得到数据和doget方法相同:
int code = httpConnection.getResponseCode();
System.out.println(code);
if(code==HttpURLConnection.HTTP_OK){
//如果正常获得,则获取值
InputStream is= httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
可选步骤:
10.连接超时:
与doGet相同。
try {
//1.生成URL(不同1>)
URL url = new URL("http://localhost:8080/MyTest/MySverlet");
//2.打开url连接
URLConnection connect =(URLConnection) url.openConnection();
//3.强制造型成httpUrlConnection
HttpURLConnection httpConnection = (HttpURLConnection) connect;
//4.设置请求方式(不同)
httpConnection.setRequestMethod("POST");
//5.设置编码格式,可接受的数据类型(固定)
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
//6.设置可以接受的序列化的java对象(固定)
httpConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//8.设置连接超时
httpConnection.setConnectTimeout(3000);//连接chaoshi
httpConnection.setReadTimeout(30000); //等待返回时间超时
//9.dopost方法特有:
httpConnection.setDoInput(true);//读取服务器的返回内容,默认为true
httpConnection.setDoOutput(true);//设置客户端可以给服务器提交数据,默认为false,post方法必须将其设置为true(必须)
httpConnection.setUseCaches(false);//设置不允许使用缓存(必须)
//10.post发送数据到服务器
String params = "name=zhangsan&password=13";
httpConnection.getOutputStream().write(params.getBytes());;//发送的是字节流
//7.(通过状态吗判断)接收服务器返回得到数据和doget方法相同
int code = httpConnection.getResponseCode();
System.out.println(code);
if(code==HttpURLConnection.HTTP_OK){
//如果正常获得,则获取值
InputStream is= httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
}catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch(SocketTimeoutException e1){
System.out.println("网络连接出问题!");
} catch(ConnectException e1){
System.out.println("服务器未开!");
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
前提:导包:
HTTPClient的jar包
//此代码在客户端的按钮点击事件中:
String name = textAreaname.getText();
String password = textAreapassword.getText();
textAreaname.setText("");
textAreapassword.setText("");
//1.生成client的builder
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MICROSECONDS);//?
//2.生成client
HttpClient client = builder.build();
//3.设置为get方法
HttpGet get = new HttpGet("http://localhost:8080/MyTest/MySverlet?name="+name+"&password="+password+"");
//4.设置服务器接收后数据的读取方式为utf-8
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
try {
//5.执行get方法得到服务器的返回的所有的数据,都存到response中。
HttpResponse response = client.execute(get);
//6.httpclient 访问服务器返回的表头,包含http状态码
StatusLine statusLine = response.getStatusLine();
//7.得到状态码
int code = statusLine.getStatusCode();
if(code==HttpURLConnection.HTTP_OK){//如果连接成功
//8.获得数据实体
HttpEntity entity = response.getEntity();
//9.获得输入流
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 (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//客户端的一个按钮点击事件中:
HttpClientBuilder builder = HttpClientBuilder.create();//1.
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client= builder.build();//2.
HttpPost post = new HttpPost("http://localhost:8080/MyTest/MySverlet");//3.与get方法不同:建post方法
NameValuePair pair1 = new BasicNameValuePair("name", "zhangsan");//4.(不同)创建NameValuePair,并放到ArrayList中
NameValuePair pair2 = new BasicNameValuePair("password", "1233");
ArrayList<NameValuePair> arraylist = new ArrayList<>();
arraylist.add(pair1);
arraylist.add(pair2);
try {
post.setEntity(new UrlEncodedFormEntity(arraylist,"UTF-8"));//5.(不同)创建实体
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//6.
HttpResponse response = client.execute(post);//7
int code = response.getStatusLine().getStatusCode();//8.
if(code == HttpURLConnection.HTTP_OK){
HttpEntity entity = response.getEntity();//9
InputStream is = entity.getContent();//10
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
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();
}
1.若在web工程中:
导入数据库的jar包,应该放在Web content 中的lib文件夹下。
2.关于HTTPClient的一些问题及线上帮助文档,请查看HTTPClient官方网站:apache