android-----提交数据到服务器的4中方式
2015-08-12 15:01
549 查看
提交数据到服务器有下面4中方式:
1.以Get方式提交
2.以Post方式提交
3.以HttpClient的Get方式提交
4以HttpClient的Post方式提交
首先在eclipse中新建一个dynamic web project ,记得设置项目的编码格式为utf-8,否则后面会出现乱码。
在src下新建一个servlet,代码如下:
接着便是搞android客户端,布局文件代码如下:
记得加上用户权限:
MainActivity文件的代码如下:
业务类的代码如下:
所用到的工具类(将输入流转换成字符串),代码如下:
效果如下图所示:
在服务器端的控制台打印如下的数据:
username=zhangsan
password=123
username=zhangsan
password=123
username=zhangsan
password=123
username=zhangsan
password=123
doPost方式提交
username=zhangsan
password=123
username=zhangsan
password=123
源代码下载地址:http://download.csdn.net/detail/dangnianmingyue_gg/8995727
1.以Get方式提交
2.以Post方式提交
3.以HttpClient的Get方式提交
4以HttpClient的Post方式提交
首先在eclipse中新建一个dynamic web project ,记得设置项目的编码格式为utf-8,否则后面会出现乱码。
在src下新建一个servlet,代码如下:
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.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //response.setContentType("text/html;charset=utf-8"); String username=request.getParameter("username"); String password=request.getParameter("password"); System.out.println("username="+username); System.out.println("password="+password); if("zhangsan".equals(username)&&"123".equals(password)){ response.getOutputStream().write("登陆成功".getBytes("utf-8")); }else{ response.getOutputStream().write("登陆失败".getBytes("utf-8")); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doPost方式提交"); doGet(request, response); } }
接着便是搞android客户端,布局文件代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <EditText android:id="@+id/et_username" android:hint="请输入用户名" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/et_password" android:hint="请输入密码" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" /> <Button android:id="@+id/bt" android:onClick="click" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GET登陆" /> <Button android:id="@+id/bt2" android:onClick="click2" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="POST登陆" /> <Button android:id="@+id/bt3" android:onClick="click3" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HttpClient GET登陆" /> <Button android:id="@+id/bt4" android:onClick="click4" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HttpClient POST登陆" /> </LinearLayout>
记得加上用户权限:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity文件的代码如下:
public class MainActivity extends Activity { private EditText et_username; private EditText et_password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_username=(EditText) findViewById(R.id.et_username); et_password=(EditText) findViewById(R.id.et_password); } public void click(View v){ final String username=et_username.getText().toString().trim(); final String password=et_password.getText().toString().trim(); new Thread(){ public void run() { if(username!=null&&password!=null){ LoginService ls=new LoginService(); final String result=ls.loginByGet(username, password); runOnUiThread(new Runnable() { @Override public void run() { if(result!=null){ Toast.makeText(MainActivity.this, result, 0).show(); }else{ Toast.makeText(MainActivity.this, "请求失败...", 0).show(); } } }); } }; }.start(); } public void click2(View v){ final String username=et_username.getText().toString().trim(); final String password=et_password.getText().toString().trim(); /** * MainActivity中调用这个类的网络操作方法,可能会导致activity的一些问题,谷歌从在android2.3版本以后,系统增加了一个类:StrictMode。这 个 类对网络的访问方式进行了一定的改变。 * StrictMode通常用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题,因为在主进程中, * UI操作和一些动作的执行是最经常用到的,它们之间会产生一定的冲突问题。将磁盘访问和网络访问从主线程中剥离可以使磁盘或者网络的访问更加流畅,提升响应度和用户体验。 * 并且在配置文件中将SDK的最低等级设为9 * * 下面这种方法是没用到Thread,但必须加上下面的这一段,若不加则会产生问题, */ /*StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy( new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); */ /*if(username!=null&&password!=null){ LoginService ls=new LoginService(); String result=ls.loginByPost(username, password); if(result!=null){ Toast.makeText(this, result, 0).show(); }else{ Toast.makeText(this, "请求失败...", 0).show(); } }*/ new Thread(){ public void run() { if(username!=null&&password!=null){ LoginService ls=new LoginService(); final String result=ls.loginByPost(username, password); /**将非UI线程加到UI线程中执行*/ runOnUiThread(new Runnable() { @Override public void run() { if(result!=null){ Toast.makeText(MainActivity.this, result, 0).show(); }else{ Toast.makeText(MainActivity.this, "请求失败...", 0).show(); } } }); } }; }.start(); } public void click3(View v){ final String username=et_username.getText().toString().trim(); final String password=et_password.getText().toString().trim(); new Thread(){ public void run() { if(username!=null&&password!=null){ LoginService ls=new LoginService(); final String result=ls.loginByHttpClientGet(username, password); /**将非UI线程加到UI线程中执行*/ runOnUiThread(new Runnable() { @Override public void run() { if(result!=null){ Toast.makeText(MainActivity.this, result, 0).show(); }else{ Toast.makeText(MainActivity.this, "请求失败...", 0).show(); } } }); } }; }.start(); } public void click4(View v){ final String username=et_username.getText().toString().trim(); final String password=et_password.getText().toString().trim(); new Thread(){ public void run() { if(username!=null&&password!=null){ LoginService ls=new LoginService(); final String result=ls.loginByHttpClientPost(username, password); /**将非UI线程加到UI线程中执行*/ runOnUiThread(new Runnable() { @Override public void run() { if(result!=null){ Toast.makeText(MainActivity.this, result, 0).show(); }else{ Toast.makeText(MainActivity.this, "请求失败...", 0).show(); } } }); } }; }.start(); } }
业务类的代码如下:
public class LoginService { public String loginByGet(String username,String password){ try { //设置编码格式,使之能够传递中文 String path="http://172.22.20.14:8080/TestJavaScript/LoginServlet?username=" +URLEncoder.encode(username, "utf-8")+"&password="+URLEncoder.encode(password, "utf-8"); URL url=new URL(path); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code=conn.getResponseCode(); if(code==200){ InputStream is=conn.getInputStream(); String text=StreamTool.streamToString(is); return text; } } catch (Exception e) { e.printStackTrace(); } return null; } public String loginByPost(String username, String password) { try { String path="http://172.22.20.14:8080/TestJavaScript/LoginServlet"; URL url=new URL(path); StringBuffer sb=new StringBuffer(); //sb.append("?"); sb.append("username="+URLEncoder.encode(username, "utf-8")+"&password="+URLEncoder.encode(password, "utf-8")); // Post方式提交的时候参数和URL是分开提交的,参数形式是这样子的:name=y&age=6 String str = sb.toString(); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setDoInput(true); conn.setDoOutput(true); // 设置请求体的类型是文本类型,表示当前提交的是文本数据 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(str.getBytes().length)); //conn.setRequestProperty("Content-Length", str.length()+""); OutputStream os=conn.getOutputStream(); os.write(str.getBytes()); int code=conn.getResponseCode(); if(code==200){ InputStream is=conn.getInputStream(); String text=StreamTool.streamToString(is); return text; } } catch (Exception e) { e.printStackTrace(); } return null; } public String loginByHttpClientGet(String username, String password) { try { HttpClient hc=new DefaultHttpClient(); String path="http://172.22.20.14:8080/TestJavaScript/LoginServlet?username=" +URLEncoder.encode(username, "utf-8")+"&password="+URLEncoder.encode(password, "utf-8"); HttpGet request=new HttpGet(path); HttpResponse response=hc.execute(request); if(response.getStatusLine().getStatusCode()==200){ HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String text=StreamTool.streamToString(is); return text; } } catch (Exception e) { e.printStackTrace(); } return null; } public String loginByHttpClientPost(String username, String password) { try { String path="http://172.22.20.14:8080/TestJavaScript/LoginServlet"; // 1. 获得一个相当于浏览器对象HttpClient,使用这个接口的实现类来创建对象,DefaultHttpClient HttpClient hc = new DefaultHttpClient(); // DoPost方式请求的时候设置请求,关键是路径 HttpPost request = new HttpPost(path); // 2.设置参数 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); NameValuePair nameValuePairs1 = new BasicNameValuePair("username", username); parameters.add(nameValuePairs1); NameValuePair nameValuePairs2 = new BasicNameValuePair("password", password); parameters.add(nameValuePairs2); HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8"); request.setEntity(entity); // 3. 执行请求 HttpResponse response = hc.execute(request); // 4. 通过返回码来判断请求成功与否 if(response.getStatusLine().getStatusCode()==200){ HttpEntity entitys = response.getEntity(); InputStream is = entitys.getContent(); String text=StreamTool.streamToString(is); return text; } } catch (Exception e) { e.printStackTrace(); } return null; } }
所用到的工具类(将输入流转换成字符串),代码如下:
public class StreamTool { public static String streamToString(InputStream is){ try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[1024]; int len=0; while((len=is.read(buffer))!=-1){ baos.write(buffer, 0, len); } baos.close(); byte[] result=baos.toByteArray(); return new String(result); } catch (Exception e) { e.printStackTrace(); return "获取失败"; } } }
效果如下图所示:
在服务器端的控制台打印如下的数据:
username=zhangsan
password=123
username=zhangsan
password=123
username=zhangsan
password=123
username=zhangsan
password=123
doPost方式提交
username=zhangsan
password=123
username=zhangsan
password=123
源代码下载地址:http://download.csdn.net/detail/dangnianmingyue_gg/8995727
相关文章推荐
- Android 5.0 SDK 下载地址
- Bitmap基本概念及在Android4.4系统上使用BitmapFactory的注意事项
- 关于Android的问号?和@符号的用法
- Android的材料设计兼容库(Design Support Library)
- Android上常见度量单位【xdpi、hdpi、mdpi、ldpi】解读
- 设置android SurfaceView背景透明
- Android上常见度量单位【xdpi、hdpi、mdpi、ldpi】解读
- Android之TabHost布局
- Android View系统学习——从setContentView说开来
- 利用android工具创建Android项目
- Android Logcat调试中的V、D、I、W、E的分别代表什么?
- android QQ第三方登录(一)
- Android嵌套滑动组件相关的文章资料
- Android开发之ExpandableListView扩展(BaseExpandableListAdapter的使用)(完整版)
- android事件分发总结
- Android中ExpandableListView控件基本使用
- Android基本概念
- Android读取SD卡内容
- Android(安卓)开发通过NDK调用JNI,使用opencv做本地c++代码开发配置方法实现边缘检测代码(2)
- 【Xamarin开发 Android 系列 13】 应用打包部署