package cn.itcast.service;
import java.io.File;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class LoginService {
/**
* 通过get请求往服务器提交数据
* @param path 请求路径
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
public boolean loginByGet(String path,String username,String password) throws Exception{
///http://192.168.1.101:8080/web/LoginServlet?name=%E7%BE%8E%E5%A5%B3&password=123456
StringBuilder sb = new StringBuilder(path);
sb.append("?");
sb.append("name=").append(URLEncoder.encode(username, "utf-8"));
sb.append("&");
sb.append("password=").append(password);
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
/**通过post请求向服务器提交数据
* post 请求首先是先把数据写入到缓存。一定要向服务器去获取数据
* @param path
* @param username
* @param password
* @return
* @throws Exception
*/
public boolean loginByPost(String path,String username,String password) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
//name=%E5%8F%B0%E6%B9%BE%E5%AF%8C%E5%B0%91&password=123456
StringBuilder sb = new StringBuilder();
sb.append("name=").append(URLEncoder.encode(username, "utf-8")).append("&");
sb.append("password=").append(password);
byte[] entity = sb.toString().getBytes();
//设置请求参数
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//实体参数的类型
conn.setRequestProperty("Content-Length", entity.length+"");//实体参数的长度
//允许对外输出
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(entity);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
/**
* 通过HttpClient 以get请求向服务器提交数据
* @param path
* @param username
* @param password
* @return
* @throws Exception
*/
public boolean loginByHttpClientGet(String path,String username,String password) throws Exception{
StringBuilder sb = new StringBuilder(path);
sb.append("?");
sb.append("name=").append(URLEncoder.encode(username, "utf-8"));
sb.append("&");
sb.append("password=").append(password);
//1 得到浏览器
HttpClient httpClient = new DefaultHttpClient();//浏览器
//2 指定请求方式
HttpGet httpGet = new HttpGet(sb.toString());
//3执行请求
HttpResponse httpResponse = httpClient.execute(httpGet);
//4判断请求是否成功
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode == 200){
return true;
}
return false;
}
/**
* 通过httpClient 以post请求向服务器发送数据
* @param path
* @param username
* @param password
* @return
* @throws Exception
*/
public boolean loginHttpClientByPost(String path,String username,String password) throws Exception{
//1 得到浏览器
HttpClient httpClient = new DefaultHttpClient();
//2 指定请求方式
HttpPost httpPost = new HttpPost(path);
//3构建请求实体的数据
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", username));
parameters.add(new BasicNameValuePair("password", password));
//4 构建实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//5 把实体数据设置到请求对象
httpPost.setEntity(entity);
//6 执行请求
HttpResponse httpResponse = httpClient.execute(httpPost);
//7 判断请求是否成功
if(httpResponse.getStatusLine().getStatusCode() == 200){
return true;
}
return false;
}
/**
* 通过httpClient 3.1 来实现文件的上传
* @param path 路径
* @param username 用户名
* @param password 密码
* @param filename 文件路径名
* @return
* @throws Exception
*/
public boolean uploadFile(String path,String username,String password,String filename) throws Exception{
//1 得到浏览器
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
//2确定请求方式
PostMethod postMethod = new PostMethod(path);
//3 确定请求的参数
Part[] parts = new Part[]{new StringPart("name", username),
new StringPart("password", password),
new FilePart("file", new File(filename))};
//4 构建实体
MultipartRequestEntity entity = new MultipartRequestEntity(parts, postMethod.getParams());
//5 设置实体
postMethod.setRequestEntity(entity);
//6 执行请求
int responseCode = httpClient.executeMethod(postMethod);
// 7判断请求是否成功
if(responseCode == 200){
return true;
}
return false;
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
try {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
String path = request.getSession().getServletContext().getRealPath("/files");
File dir = new File(path);
System.out.println(path);
if(!dir.exists()){
dir.mkdirs();
}
for(FileItem item:items){
if(item.isFormField()){//文本
String name = item.getFieldName();
String value = item.getString();
System.out.println(name + " = " + value);
}else{//文件
String filename = item.getName();
File file = new File(dir, getFilename(filename));
item.write(file);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
doGet(request, response);
}
}
//得到文件名称
private String getFilename(String filename){
if(filename.contains("\\")){
return filename.substring(filename.lastIndexOf("\\")+1);
}
return filename;
}