1:什么是HTTP?
2:get 与post
get只有一个流,参数附加在url后,地址行显示要传送的信息,大小个数有严格限制且只能是字符串。
post的参数是通过另外的流传递的, 不通过url,所以可以很大,也可以传递二进制数据,如文件的上传。
1、安全
GET调用在URL里显示正传送给SERVLET的数据,这在系统的安全方面可能带来问题,例如用户名和密码等
POST就可以在一定程度上解决此类问题
2、服务器接收方式
服务器随机接受GET方法的数据,一旦断电等原因,服务器也不知道信息是否发送完毕
而POST方法,服务器先接受数据信息的长度,然后再接受数据
3、form运行方式
当form框里面的method为get时,执行doGet方法
当form框里面的method为post时,执行doPost方法
4、容量限制
GET方法后面的信息量字节大小不要超过1.3K,而Post则没有限制
最后说明的是:
你可以用service()来实现,它包含了doget和dopost ;service方法是接口中的方法,servlet容器把所有请求发送到该方法,该方法默认行为是转发http请求到doXXX方法中,如果你重载了该方法,默认操作被覆盖,不再进行转发操作!
service()是在javax.servlet.Servlet接口中定义的, 在 javax.servlet.GenericServlet
中实现了这个接口, 而 doGet/doPost 则是在 javax.servlet.http.HttpServlet 中实现的, javax.servlet.http.HttpServlet 是 javax.servlet.GenericServlet 的子类.
所有可以这样理解, 其实所有的请求均首先由 service() 进行处理, 而在 javax.servlet.http.HttpServlet 的 service() 方法中, 主要做的事情就是判断请求类型是 Get 还是 Post, 然后调用对应的 doGet/doPost 执行.
3:HTTP编程
1>:使用get方式获取服务器端的一张图片,放在本地==》获取服务器的东西用get方式更好
package get; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtil { /** * 使用get方式获取服务器端的一张图片 * @throws IOException */ public static InputStream getInputStream(String path) throws IOException { URL url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //设置请求方式 con.setRequestMethod("GET");//默认请求方式是get //设置连接超时时间 con.setConnectTimeout(5000); //设置可以从服务器端读取数据 con.setDoInput(true);//默认值就是true InputStream in = null; //判断服务器端的响应码是否是200 if(con.getResponseCode()==200) { in = con.getInputStream(); } return in; } public static void makeImg(InputStream in) throws IOException { FileOutputStream fos = new FileOutputStream("file\img.jpg"); byte[] b = new byte[1024]; int len = 0; //读取服务器返回的图片数据 while ((len = in.read(b))!=-1) { fos.write(b,0,len); } fos.close(); in.close(); } }
package get; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { String path ="http://localhost:9999/day16/img2.jpg"; HttpUtil.makeImg(HttpUtil.getInputStream(path)); } }
2:使用post方式提交用户名和密码,并获取服务器端的验证结果==》需要返回数据就用post,服务器端代码上篇博客中有
package post; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; 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.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class HttpUtil { public static String sendByPost(String path,Map<String,String> params,String encode) throws ClientProtocolException, IOException { //先把要提交的每对儿数据封装成NameValuePair类型的 List<NameValuePair> list = new ArrayList<NameValuePair>(); for(Map.Entry<String, String> en:params.entrySet()) { list.add(new BasicNameValuePair(en.getKey(),en.getValue())); } //把要提交的数据组织成提交的格式 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode); //创建提交方式对象 HttpPost post = new HttpPost(path); post.setEntity(entity); //创建执行提交的对象 HttpClient client = new DefaultHttpClient(); //执行提交 HttpResponse response = client.execute(post); if(response.getStatusLine().getStatusCode()==200) { InputStream in = response.getEntity().getContent(); return getResult(in,encode); } return null; } private static String getResult(InputStream in, String encode) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; int len = 0; while((len = in.read(arr))!=-1) { bos.write(arr,0,len); } return new String(bos.toByteArray(),encode); } }
package post; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Test { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Map<String,String> params = new HashMap<String, String>(); params.put("username", "李鹏"); params.put("pwd","123456"); String path = "http://localhost:9999/day16/servlet/LoginServlet"; String encode= "utf-8"; System.out.println(HttpUtils.sendByPost(path, params, encode)); } }
3:使用apache中jar包提供的简洁方法提交用户名和密码,并获取服务器端的验证结果
package apache; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class HttpUtil { public static String sendByPost(String path,HashMap<String,String> params,String encode) throws ClientProtocolException, IOException { //先把要提交的每对儿数据封装成NameValuePair类型的 List<NameValuePair> list = new ArrayList<NameValuePair>(); for(Map.Entry<String, String> en:params.entrySet()) { list.add(new BasicNameValuePair(en.getKey(),en.getValue())); } //把要提交的数据组织成提交的格式 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode); //创建提交方式对象 HttpPost post = new HttpPost(path); post.setEntity(entity); //创建执行提交的对象 HttpClient client = new DefaultHttpClient(); //执行提交 HttpResponse response = client.execute(post); if(response.getStatusLine().getStatusCode()==200) { InputStream in = response.getEntity().getContent(); return getResult(in,encode); } return null; } private static String getResult(InputStream in, String encode) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; int len = 0; while((len = in.read(arr))!=-1) { bos.write(arr,0,len); } return new String(bos.toByteArray(),encode); } }
package appache; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Test { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Map<String,String> params = new HashMap<String, String>(); params.put("username", "李鹏"); params.put("pwd","123456"); String path = "http://localhost:9999/day16/servlet/LoginServlet"; String encode= "utf-8"; System.out.println(HttpUtil.sendByPost(path, params, encode)); } }
4:使用apach上传文件
package com.qianfeng.upload; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.FormBodyPart; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; /** * 该类实现文件上传的功能 * @author qq * */ public class FileUpload { public void fileUpload(final String path, final File file, final HashMap<String,String> params, final String encode, final CallBack callBack) { //在一个子线程中实现文件上传 new Thread(new Runnable(){ @Override public void run() { HttpPost post = new HttpPost(path); HttpClient client = new DefaultHttpClient(); HttpResponse response = null; //把上传的文件和上传的参数组织成表单提交的格式 MultipartEntity entity = new MultipartEntity(); //处理上传的文件 FileBody body = new FileBody(file); FormBodyPart bodyPart = new FormBodyPart("form",body); entity.addPart(bodyPart); //处理上传的参数 for(Map.Entry<String, String> en:params.entrySet()) { try { entity.addPart(en.getKey(), new StringBody(en.getValue())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } post.setEntity(entity); try { //执行提交 response = client.execute(post); if(response.getStatusLine().getStatusCode()==200){ String result = EntityUtils.toString(response.getEntity()); JSONObject obj = new JSONObject(result); callBack.getResult(obj); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } } //定义回调接口 interface CallBack { public void getResult(JSONObject obj); }
package com.qianfeng.upload; import java.io.File; import java.util.HashMap; import org.json.JSONObject; public class Test { /** * @param args */ public static void main(String[] args) { String path = "http://localhost:8080/FileUploadServer/servlet/UploadServlet"; HashMap<String,String> params = new HashMap<String,String>(); params.put("username", "admin"); params.put("password", "123"); File file = new File("file\tou1.jpg"); FileUpload fileUpload = new FileUpload(); fileUpload.fileUpload(path, file, params, "utf-8", new CallBack(){ @Override public void getResult(JSONObject obj) { System.out.println(obj.toString()); } }); } }