Android笔记 get方式提交数据到服务器 避免乱码 demo

http://download.csdn.net/detail/u011109881/8042001源代码

根据传智播客张泽华视频54-57写出

文中加粗的是解决乱码问题

A web端

1login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
<form action="LoginServlet" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

2新建LoginServlet

package com.jkd.test;

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

/**
 * 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 {
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		<strong>System.out.println("Username="+new String(username.getBytes("iso-8859-1"),"utf-8"));</strong>
		System.out.println("Password="+password);
		if("zhansan".equals(username)&&"123".equals(password)){
			<strong>response.getOutputStream().write("登陆成功".getBytes("utf-8"));</strong>
		}else{
			<strong>response.getOutputStream().write("登录失败".getBytes("utf-8"));</strong>
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}

B Android客户端

先在清单文件加权限Internet

1布局文件

<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:text="张三"
        android:id="@+id/et_username"
        android:hint="请输入用户名"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <EditText
        android:hint="请输入密码"
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" />

    <Button
        android:onClick="click"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录" />
    
    <Button
        android:onClick="click2"
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post登录" />

</LinearLayout>

2工具类 将字符流转成字符串

package com.example.a54_senddatatoservice.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTools {
public static String readInputStream(InputStream is) {
		
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		int length=0;
		byte [] buffer =new byte[1024];
		try {
			while ((length=is.read(buffer))!=-1) {
				baos.write(buffer,0,length);
			}
			is.close();
			baos.close();
			byte [] result=baos.toByteArray();
			//试着解析result里的字符串
			<strong>String temp=new String(result);
			if (temp.contains("utf-8")) {
				return temp;
			}else if(temp.contains("gb2312")){
				return new String(result,"gb2312");
			}
			else if(temp.contains("gbk")){
				return new String(result,"gbk");
			}else {
				return temp;
			}</strong>
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "获取失败";
		}
		
	}
}

3服务类 两个静态方法 

package com.example.a54_senddatatoservice.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.example.a54_senddatatoservice.utils.StreamTools;

public class LoginService {
	/**
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByGet(String username, String password) {
		// 提交数据到服务器
		// 拼装路径

		try {
			String path = "http://10.10.5.31:8080/web/LoginServlet?username="
					+ <strong>URLEncoder.encode(username, "UTF-8")</strong> + "&password="
					+ password;
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			if (code == 200) {
				// 请求成功
				InputStream is = conn.getInputStream();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param username
	 * @param password
	 * @return null---->error text--->success
	 */
	public static String loginByPost(String username, String password) {
		// 提交数据到服务器
		// 拼装路径

		try {
			String path = "http://10.10.5.31:8080/web/LoginServlet";
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("POST");
			// 准备数据
			String data = "username=" +<strong> URLEncoder.encode(username, "UTF-8")</strong>
					+ "&password=" + password;
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", data.length() + "");

			// post实际上是浏览器把数据写给了服务器
			conn.setDoOutput(true);//UrlConnection允许向外传数据
			OutputStream os = conn.getOutputStream();
			os.write(data.getBytes());
			int code = conn.getResponseCode();
			if (code == 200) {
				// 请求成功
				InputStream is = conn.getInputStream();
				String text = StreamTools.readInputStream(is);
				return text;

			} else {
				return null;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}

4主界面 包括俩个点击事件

package com.example.a54_senddatatoservice;

import com.example.a54_senddatatoservice.service.LoginService;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	// 要配合web项目 目录位于E:\study\soft\Android\gaobo\android\web
	private EditText et_username;
	private EditText et_password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_password = (EditText) findViewById(R.id.et_password);
		et_username = (EditText) findViewById(R.id.et_username);
	}

	public void click(View view) {
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();

		new Thread() {
			public void run() {
				final String result = LoginService.loginByGet(username,
						password);
				if (result != null) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}

	public void click2(View view) {
		final String username = et_username.getText().toString().trim();
		final String password = et_password.getText().toString().trim();

		new Thread() {
			public void run() {
				final String result = LoginService.loginByPost(username,
						password);
				if (result != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, result,
									Toast.LENGTH_SHORT).show();
						}
					});
				} else {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(MainActivity.this, "请求失败",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			};
		}.start();

	}

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值