zoukankan      html  css  js  c++  java
  • android向服务器提交数据的几种方式

    GET:

     1 public static String loginByGet(String username,String password){
     2         try {
     3             //定义路径
     4             String path="http://192.168.1.102:8084/androidServer/loginServlet?username="
     5                     +URLEncoder.encode(URLEncoder.encode(username,"UTF-8"), "UTF-8")+"&password="+password;
     6             URL url=new URL(path);//包装路径
     7             HttpURLConnection conn=(HttpURLConnection) url.openConnection();//打开连接
     8             conn.setConnectTimeout(5000);//设置连接超时
     9             conn.setReadTimeout(5000);//设置读取超时
    10             conn.setRequestMethod("GET");//设置提交方式
    11             int code=conn.getResponseCode();//获取响应码
    12             if(code==200){
    13                 //请求成功
    14                 InputStream is=conn.getInputStream();//获取输入流
    15                 ByteArrayOutputStream baos=new ByteArrayOutputStream();//定义字节数组输出流
    16                 int len=0;
    17                 byte[] buffer=new byte[1024];//设置缓存
    18                 while((len=is.read(buffer))!=-1){
    19                     baos.write(buffer);//将缓存中的字节数据读入字节数组输出流
    20                 }
    21                 byte[] result=baos.toByteArray();//转换成字节数组
    22                 String str=new String(result);//转换成字符串
    23                 return str;
    24             }else{
    25                 return null;
    26             }
    27         } catch (Exception e) {
    28             e.printStackTrace();
    29             return null;
    30         }
    31     }

    POST:

     1 public static String loginByPost(String username,String password){
     2         String path="http://192.168.1.102:8084/androidServer/loginServlet";//定义路径
     3         try {
     4             URL url=new URL(path);
     5             HttpURLConnection conn=(HttpURLConnection) url.openConnection();//打开连接
     6             //编码数据(post提交中文只编码一次,编码两次亦可,GET需要编码两次)
     7             String data="username="+URLEncoder.encode(URLEncoder.encode(username,"UTF-8"), "UTF-8")+"&password="+password;
     8             conn.setConnectTimeout(5000);
     9             conn.setReadTimeout(5000);
    10             conn.setRequestMethod("POST");
    11             //一下几项必须设置
    12             conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置内容类型
    13             conn.setRequestProperty("Content-Length", data.length()+"");//设置内容长度
    14             conn.setDoOutput(true);//设置允许输出
    15             OutputStream os=conn.getOutputStream();//获取输出流
    16             os.write(data.getBytes());//输出数据
    17             int code=conn.getResponseCode();
    18             if(code==200){
    19                 //请求成功
    20                 InputStream is=conn.getInputStream();
    21                 ByteArrayOutputStream baos=new ByteArrayOutputStream();
    22                 int len=0;
    23                 byte[] buffer=new byte[1024];
    24                 while((len=is.read(buffer))!=-1){
    25                     baos.write(buffer);
    26                 }
    27                 byte[] result=baos.toByteArray();
    28                 String str=new String(result);
    29                 return str;
    30             }else{
    31                 return null;
    32             }
    33         } catch (Exception e) {
    34             e.printStackTrace();
    35             return null;
    36         }
    37     }

    HttpClient GET(模拟浏览器):

     1 public static String loginByClientGet(String username,String password){
     2         String str=null;
     3         try {
     4             //打开一个浏览器
     5             HttpClient client = new DefaultHttpClient();
     6             //输入地址
     7             String path = "http://192.168.1.102:8084/androidServer/loginServlet?username="
     8                     + URLEncoder.encode(URLEncoder.encode(username, "UTF-8"),"UTF-8") + "&password=" + password;
     9             HttpGet get = new HttpGet(path);//构建请求对象
    10             //敲回车
    11             HttpResponse response = client.execute(get);//获得相应结果
    12             if(response.getStatusLine().getStatusCode()==200){//判断状态码
    13                 InputStream is=response.getEntity().getContent();//获取内容输入流
    14                 ByteArrayOutputStream baos=new ByteArrayOutputStream();
    15                 int len=0;
    16                 byte[] buffer=new byte[1024];
    17                 while((len=is.read(buffer))!=-1){
    18                     baos.write(buffer);
    19                 }
    20                 byte[] result=baos.toByteArray();
    21                 str=new String(result);
    22                 return str;
    23             }
    24         } catch (Exception e) {
    25             e.printStackTrace();
    26             return str;
    27         }
    28         return null;
    29     }

     HttpClient POST:

     1 public static String loginByClientPOST(String username,String password){
     2         String str=null;
     3         try {
     4             //打开一个浏览器
     5             HttpClient client = new DefaultHttpClient();
     6             //输入地址
     7             String path = "http://192.168.1.102:8084/androidServer/loginServlet";
     8             HttpPost post = new HttpPost(path);
     9             //制定要提交的数据实体
    10             List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    11             parameters.add(new BasicNameValuePair("username", username));//设置数据
    12             parameters.add(new BasicNameValuePair("password", password));
    13             post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
    14             
    15             //敲回车(与get一致)
    16             HttpResponse response = client.execute(post);//获得相应结果
    17             if(response.getStatusLine().getStatusCode()==200){//判断状态码
    18                 InputStream is=response.getEntity().getContent();//获取内容输入流
    19                 ByteArrayOutputStream baos=new ByteArrayOutputStream();
    20                 int len=0;
    21                 byte[] buffer=new byte[1024];
    22                 while((len=is.read(buffer))!=-1){
    23                     baos.write(buffer);
    24                 }
    25                 byte[] result=baos.toByteArray();
    26                 str=new String(result);
    27                 return str;
    28             }
    29         } catch (Exception e) {
    30             e.printStackTrace();
    31         }
    32         return "";
    33     }

    调用:

     1 public void login(View v){
     2         final String username=et_username.getText().toString().trim();
     3         final String password=et_password.getText().toString().trim();
     4         
     5         new Thread(){
     6             public void run() {
     7                 final String str=Service.loginByGet(username, password);
     8                 if(str!=null){
     9                     runOnUiThread(new Runnable() {//joinUI线程更新界面
    10                         public void run() {
    11                             Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
    12                         }
    13                     });
    14                 }else{
    15                     runOnUiThread(new Runnable() {
    16                         public void run() {
    17                             Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
    18                         }
    19                     });
    20                 }
    21             };
    22         }.start();
    23     }

    服务端servlet

     1 public void doGet(HttpServletRequest request, HttpServletResponse response)
     2             throws ServletException, IOException {
     3         response.setContentType("text/html;charset=utf-8");//设置响应类型和编码
     4         PrintWriter out = response.getWriter();//获取输出流
     5         request.setCharacterEncoding("utf-8");//设置处理请求编码
     6         String username=URLDecoder.decode(request.getParameter("username"),"utf-8");//解码请求参数
     7         String password=request.getParameter("password");
     8         //System.out.println("username="+username+",password="+password);
     9         if("admin".equals(username)&&"123".equals(password)){
    10             out.print("登陆成功");
    11         }else{
    12             out.print("登录失败");
    13         }
    14     }
    15 
    16     public void doPost(HttpServletRequest request, HttpServletResponse response)
    17             throws ServletException, IOException {
    18 
    19         doGet(request, response);
    20     }
  • 相关阅读:
    使用ConcurrentLinkedQueue惨痛的教训【转】
    非阻塞算法在并发容器中的实现【转】
    ConcurrentLinkedQueue的实现原理分析
    jQuery Validate验证框架详解
    Java中的ReentrantLock和synchronized两种锁定机制的对比
    ReentrantLock与Condition
    Java线程创建的两种方式
    JAVA并发:深入分析volatile
    Java线程同步
    JAVA jstack命令详解
  • 原文地址:https://www.cnblogs.com/wangjiajun/p/3413366.html
Copyright © 2011-2022 走看看