网络访问httpconnection httpclient 文件传输

来源:互联网 发布:给游戏做美工需要什么 编辑:程序博客网 时间:2024/06/06 00:47
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=123456StringBuilder 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=123456StringBuilder 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 stubboolean isMultipart = ServletFileUpload.isMultipartContent(request);if(isMultipart){try {// Create a factory for disk-based file itemsFileItemFactory factory = new DiskFileItemFactory();// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requestList<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 blocke.printStackTrace();}}else{doGet(request, response);}}//得到文件名称private String getFilename(String filename){if(filename.contains("\\")){   return filename.substring(filename.lastIndexOf("\\")+1);}return filename;}


0 0
原创粉丝点击