一个简单地应用--从客户端向服务器发送数据.post,get.httpclientget,httpclinetpost,文件上传.



//http://192.168.138.1:8080/web/LoginServlethttp://192.168.138.1:8080/加上web包名加上 <url-pattern>/LoginServlet</url-pattern>中的/LoginServlet.

//http://192.168.138.1:8080/web/LoginServlet?name=zhangsan&password=123456会显示login succes.

//http://192.168.138.1:8080/web/LoginServlet是请求的客户端请求的bathpath.

//tomcat服务器容器编码iso8859-1.

//在导入文件的时候,服务器段记得导包.

package cn.itcast.login;

import cn.itcast.login.service.DataService;
import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts.Data;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DemoActivity extends Activity implements OnClickListener {
	private EditText mEtName;
	private EditText mEtPassword;
	private EditText mEtFilePath;
	private Button mBtLogin;
	private Button mBtLoginPost;
	private Button mBtLoginClientGet;
	private Button mBtLoginClientPost;
	private Button mBtLoginClientPostFile;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mEtName = (EditText) this.findViewById(R.id.et_name);
        mEtPassword = (EditText) this.findViewById(R.id.et_password);
        mBtLogin = (Button) this.findViewById(R.id.bt_login);
        mBtLoginPost = (Button)this.findViewById(R.id.bt_login_post);
        mBtLoginClientGet =  (Button)this.findViewById(R.id.bt_login_client_get);
        mBtLoginClientPostFile =  (Button)this.findViewById(R.id.bt_login_client_post_file);
        mBtLoginClientPost =   (Button)this.findViewById(R.id.bt_login_client_post);
        mEtFilePath = (EditText)this.findViewById(R.id.et_file_path);
        mBtLogin.setOnClickListener(this);
        mBtLoginPost.setOnClickListener(this);
        mBtLoginClientGet.setOnClickListener(this);
        mBtLoginClientPost.setOnClickListener(this);
        mBtLoginClientPostFile.setOnClickListener(this);
    }


	@Override
	public void onClick(View v) {
		String name = mEtName.getText().toString().trim();
		String password = mEtPassword.getText().toString().trim();
		if("".equals(name)||"".equals(password)){
			Toast.makeText(this, "用户名或密码不能为空", 0).show();
			return;
		}
		String path = getResources().getString(R.string.servleturl);
		switch (v.getId()) {
		case R.id.bt_login:

			// 通过get请求 发送数据到服务器 
			
			try {
				String result = DataService.sendDataByGet(path, name, password);
				Toast.makeText(this, result, 0).show();
			} catch (Exception e) {
				Toast.makeText(this, "访问网路异常", 0).show();
				e.printStackTrace();
			}
			
			break;
		case R.id.bt_login_post:
			try {
				String result =  DataService.sendDataByPost(path, name, password);
				Toast.makeText(this, result, 0).show();
			} catch (Exception e) {
				Toast.makeText(this, "访问网路异常", 0).show();
				e.printStackTrace();
			}
			break;
		case R.id.bt_login_client_get:
			try {
				String result = DataService.sendDataByHttpClientGet(path, name, password);
				Toast.makeText(this, result, 0).show();
			} catch (Exception e) {
				Toast.makeText(this, "访问网路异常", 0).show();
				e.printStackTrace();
			}
			
			
			break;
		case R.id.bt_login_client_post:
			try {
				String result = DataService.sendDataByHttpClientPost(path, name, password);
				Toast.makeText(this, result, 0).show();
			} catch (Exception e) {
				Toast.makeText(this, "访问网路异常", 0).show();
				e.printStackTrace();
			}
			break;	
		case R.id.bt_login_client_post_file:
			try {
				String filepath = mEtFilePath.getText().toString().trim();
				if("".equals(filepath)){
					Toast.makeText(this, "路径不能为空", 0).show();
					return ;
				}
				String result = DataService.sendDataByHttpClientPost(path, name, password, filepath);
				Toast.makeText(this, result, 0).show();
				System.out.println(new String( result.getBytes("iso8859-1"),"utf-8"));
				
			} catch (Exception e) {
				Toast.makeText(this, "访问网路异常", 0).show();
				e.printStackTrace();
			}
			break;	
		}
		
	}
}

package cn.itcast.login.service;

import java.io.File;
import java.io.InputStream;
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;

import cn.itcast.login.util.StreamTool;

public class DataService {

 /**
  * 通过get请求提交数据到服务器
  *
  * @param path
  *            服务器servlet的地址
  * @param name
  *            用户名
  * @param password
  *            密码
  * @return 服务器返回回来的string数据
  */
 public static String sendDataByGet(String path, String name, String password)
   throws Exception {
  @SuppressWarnings("deprecation")
      // 如果是中文的话,就必须要这句.URLEncoder.encode(name); 
  String param1 = URLEncoder.encode(name);
  @SuppressWarnings("deprecation")
  String param2 = URLEncoder.encode(password);
  URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  
  // 数据并没有发送给服务器
  conn.setRequestMethod("GET");
  conn.setReadTimeout(5000);
  
  // 获取服务器返回的信息 的时候数据才会发送给服务器
  InputStream is = conn.getInputStream();
  byte[] result = StreamTool.getBytes(is);

  return new String(result);
 }

 // get post
 // get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
 // post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
 //form表单对应的界面 在服务器创建出来.  服务器创建Login.jsp页面,更改charset=utf-8
 /**
  * 采用post的方式 提交数据到服务器
  *
  * @param path
  *            服务器servlet的地址
  * @param name
  *            用户名
  * @param password
  *            密码
  * @return 服务器返回的数据信息
  * @throws Exception
  */
 public static String sendDataByPost(String path, String name,
   String password) throws Exception {
 //编码
  String param1 = URLEncoder.encode(name);
  String param2 = URLEncoder.encode(password);
  URL url = new URL(path);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  String data = "name=" + param1 + "&password=" + param2;
//一定要显示地指定
  conn.setRequestMethod("POST");
  conn.setConnectTimeout(5000); 
  // 设置 http协议可以向服务器写数据
  conn.setDoOutput(true);
  
  // 设置http协议的消息头.Content-Type表单类型  .Content-Length数据的长度
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", data.length() + "");
  //得到输出流.把我们准备好的数据写给服务器.
  OutputStream os = conn.getOutputStream();
  // 把我们准备好的data数据写给服务器
  os.write(data.getBytes());
  // httpurlconnection 底层实现    outputstream 是一个缓冲输出流
  
  // 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
  int code = conn.getResponseCode();
  if (code == 200) {
   InputStream is = conn.getInputStream();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  } else {
   throw new IllegalStateException("服务器状态异常");
  }
 }
 
 
 /**
  * httpclient 浏览器的简单包装
  * new HttpClient 就相当于得到了一个浏览器
  */
 public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
  
  //1. 获取到一个浏览器的实例    
  HttpClient client = new DefaultHttpClient();
  //2. 准备请求的地址 ..完整的地址
  String param1 = URLEncoder.encode(name);
  String param2 = URLEncoder.encode(password);
  HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
  
  //3. 敲回车 发请求
  //HttpResponse获取的信息.
  HttpResponse  ressponse = client.execute(httpGet);
  //得到状态行,就是第一行.之后得到状态行的状态码
  int code = ressponse.getStatusLine().getStatusCode();
  if(code == 200){
   //ressponse.getEntity()得到返回实体.后得到返回的实体的流
   InputStream is  =ressponse.getEntity().getContent();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 }
 /**
  * httpclient post浏览器的简单包装
  * new HttpClient 就相当于得到了一个浏览器
  */
 public static String sendDataByHttpClientPost(String path , String name,String password) throws Exception{
  
  //1. 获取到一个浏览器的实例
  HttpClient client = new DefaultHttpClient();
  //2. 准备要请求的 数据类型
  //地址path是basepath.
  HttpPost httppost = new HttpPost(path);
  // 键值对
  //NameValuePair是个接口
  List< NameValuePair> parameters = new ArrayList<NameValuePair>();
  //BasicNameValuePair是个实现类
  parameters.add(new BasicNameValuePair("name", name));
  parameters.add(new BasicNameValuePair("password", password));
  
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
  
  
  //3.设置post请求的数据实体
  httppost.setEntity(entity);
  
  //4. 发送数据给服务器
  HttpResponse  ressponse = client.execute(httppost);
  int code = ressponse.getStatusLine().getStatusCode();
  if(code == 200){
   InputStream is  =ressponse.getEntity().getContent();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 }
 
 /**
  * 提交数据给服务器 带一个文件
  * @param path
  * @param name
  * @param password
  * @param filepath 文件在手机上的路径
  *
  * @return
  * @throws Exception
  */
 public  static String sendDataByHttpClientPost(String path , String name,String password ,String filepath) throws Exception{
  // 实例化上传数据的 数组  part []
  Part[] parts = {new StringPart("name", name),
      new StringPart("password", password),
      new FilePart("file", new File(filepath))};
  
  PostMethod filePost = new PostMethod(path);
  
  
  filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
  org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams()
          .setConnectionTimeout(5000);
  int status = client.executeMethod(filePost);
  if(status==200){
   
   System.out.println( filePost.getResponseCharSet());
   String result = new String(filePost.getResponseBodyAsString());
   String ha = new String ( result.getBytes("ISO-8859-1"),"UTF-8");
   System.out.println(ha);
   
   System.out.println("--"+result);
   return result;
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 
 }
}

的代码服务器

package cn.itcast.web;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// request.getParameter 
		String name = request.getParameter("name");
		if (name != null) {
			name = new String(name.getBytes("iso8859-1"), "utf-8");

		}

		String password = request.getParameter("password");
		System.out.println(name);
		System.out.println(password);

		if ("zhangsan".equals(name) && "123456".equals(password)) {
			response.getOutputStream().write("login succes".getBytes());
		} else {
			response.getOutputStream().write("login failed".getBytes());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// doGet(request, response);
	
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			String realpath = request.getSession().getServletContext()
					.getRealPath("/files");
			System.out.println(realpath);
			File dir = new File(realpath);
			if (!dir.exists())
				dir.mkdirs();

			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem item : items) {
					if (item.isFormField()) {
						String name1 = item.getFieldName();// 
						String value = item.getString("UTF-8");//
						System.out.println(name1 + "=" + value);
					} else {
						item.write(new File(dir, System.currentTimeMillis()
								+ item.getName().substring(
										item.getName().lastIndexOf("."))));
					}
				}

				response.getOutputStream().write("你好".getBytes("iso-8859-1"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			doGet(request, response);
		}

	}

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值