Android提交数据到服务器分为:通过get方式提交数据到服务器、采用post方式提交数据到服务器、采用httpclient发送get请求、采用httpclient发送post请求、采用httpclient上传数据文件。

其中通过get方式和post方式提交数据到服务器为最基本的方式,他们需要程序员拼装出发送的get请求,如本例中的URL url = new URL(path + "?name=" + param1 + "&password=" + param2);代码,通过StreamTool.getBytes()方法得到服务器返回的内容,值得注意的是在使用post提交数据时要设置 http协议可以向服务器写数据conn.setDoOutput(true);设置http协议的消息头conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", data.length() + "");采用httpclient发送get请求和post请求是:获取到一个浏览器的实例HttpClient client = new DefaultHttpClient(); 准备请求的地址String param1 = URLEncoder.encode(name);String param2 = URLEncoder.encode(password);HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password="+ param2); 敲回车 发请求HttpResponse ressponse = client.execute(httpGet);最后就是采用httpclient上传数据文件,要实现此功能必须依赖的包有commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.jar,切记!!!!!!

下面贴上具体代码:

首先是模拟服务器端的代码,要实现文件上传需要的包为commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar

模拟登陆界面login.jsp:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>模拟登陆</title></head><body><form action="/web2/LoginServlet" method="post"ENCTYPE="multipart/form-data">用户名:<input name="name" value="12" type="text"> <br>密码:<input type="password" value="12" name="password"><br> <input name="file" type="file"> <input value="提交"type="submit"> <br></form></body></html>
处理登陆请求代码LoginServlet.java:
package big.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 {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 ((name.equals("chao")) && (password.equals("111111"))) {response.getOutputStream().write("login success".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 {boolean isMultipart = ServletFileUpload.isMultipartContent(request);System.out.println(isMultipart);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("."))));}}} catch (Exception e) {e.printStackTrace();}} else {System.out.println("else");doGet(request, response);}}}
下面为Android端代码:

首先是布局文件main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <EditText        android:id="@+id/et_name"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="@string/input_name" />    <EditText        android:id="@+id/et_password"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="@string/input_password" />    <EditText        android:id="@+id/et_file_path"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="/mnt/sdcard/bing.txt"        android:hint="@string/input_filepath" />    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/get_login"            android:id="@+id/bt_login"            android:layout_alignParentRight="true"             />    </RelativeLayout>    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/post_login"            android:id="@+id/bt_login_post"            android:layout_alignParentRight="true"             />    </RelativeLayout>        <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/client_get_login"            android:id="@+id/bt_login_client_get"            android:layout_alignParentRight="true"             />    </RelativeLayout>            <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/client_post_login"            android:id="@+id/bt_login_client_post"            android:layout_alignParentRight="true"             />    </RelativeLayout>                <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/client_post_login_with_file"            android:id="@+id/bt_login_client_post_file"            android:layout_alignParentRight="true"             />    </RelativeLayout></LinearLayout>

清单文件AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="cn.itcast.login"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" />    <uses-permission android:name="android.permission.INTERNET"/>    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".DemoActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
核心代码登场

工具类StreamTool.java:

package cn.itcast.login.util;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool {/** * 把一个inputstream里面的内容转化成一个byte[]  */public static byte[] getBytes(InputStream is) throws Exception{ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while((len = is.read(buffer))!=-1){bos.write(buffer, 0, len);}is.close();bos.flush();byte[] result = bos.toByteArray();System.out.println(new String(result));return  result;}}
服务核心文件DataService.java:
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 {String param1 = URLEncoder.encode(name);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表单的形式 流的方式写到服务器/** * 采用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协议的消息头conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", data.length() + "");// 把我们准备好的data数据写给服务器OutputStream os = conn.getOutputStream();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 ressponse = client.execute(httpGet);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("服务器状态异常");}}public static String sendDataByHttpClientPost(String path, String name,String password) throws Exception {// 1. 获取到一个浏览器的实例HttpClient client = new DefaultHttpClient();// 2. 准备要请求的 数据类型HttpPost httppost = new HttpPost(path);// 键值对 parameters就是提交的内容 是键值对的形式List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("name", name));parameters.add(new BasicNameValuePair("password", password));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");// entity接受两个参数,第一个位list集合,第二个是数据类型// 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("服务器状态异常");}}}
主文件DemoActivity.java:
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);    }@Overridepublic 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;}}}



更多相关文章

  1. Android有序广播OrderedBroadcast
  2. Android(安卓)Studio 使用jdbc远程连接阿里云主机web数据库(逃坑)
  3. Android(Xamarin)之旅(五)
  4. Android(安卓)数据存储(一) Preference的使用
  5. Android中关于C2DM开发的一点总结
  6. Android数据库SQLite性能优化技巧
  7. android-pull方式解析xml文件以及XML文件的序列化
  8. Android(安卓)HttpURLConnection及HttpClient对比
  9. Android+Jquery Mobile学习系列(5)-SQLite数据库

随机推荐

  1. android listview 右滑删除(android 项目
  2. Android(安卓)studio 解决Android(安卓)L
  3. WebRTC
  4. widget入门
  5. Android studio怎样隐藏标题栏
  6. Android 2.3的camera的虚拟对焦的去除
  7. 【Android基础】Android开发学习笔记
  8. 永久改变android 模拟器分区大小
  9. 【Android】配置文件属性说明
  10. Android声音播放实例代码