使用HttpURLConnection采用get方式请求数据-----乱码问题

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012360634/article/details/45127435

1. 在子线程中改变ui,用handle通信,还可以用

// 执行任务在主线程中,除handle外
    runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 就是在主线程中操作
								Toast.makeText(MainActivity.this, state, 0).show();
							}
						}

2.    ******根据流返回一个字符串;代码---

3.    添加权限Internet

4.   乱码问题:

   MyEclipse:默认采用的是iso8859-1

   模拟器默认采用的是utf-8

4.    服务器方面:

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
String username =request.getParameter(“username”);//采用的编码是iso8859-1
String password =request.getParameter(“password”);
//采用iso8859-1的编码对姓名进行逆转,转换成字节数组,再使用utf-8编码对数据进
//行转换成字符串
username=new String(username.getBytes(“iso8859-1”),”utf-8”);
password=new String(password.getBytes(“iso8859-1”),”utf-8”);
If(“李四”.equals(username)&&”123”.equals(password)){
//getBytes默认情况下,使用的iso8859-1的编码,但如果发现码表中没有当前字符,会//使用当前系统的默认编码:GBK
  Response.getOutputStream().write(“登陆成功”.getBytes());
}else{
Response.getOutputStream().write(“登陆失败”.getBytes());
}
}


5.客户端访问:localhost:8080/ServerItheima28/servlet/LoginServlet?username=lisi&password=123

6.代码

public class MainActivity extends Activity {

	private EditText etUserName;
	private EditText etPassword;

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

	public void doGet(View v) {
		final String userName = etUserName.getText().toString();
		final String password = etPassword.getText().toString();
		
		new Thread(
				new Runnable() {
					
					@Override
					public void run() {
						// 使用get方式抓去数据,返回登陆结果
						final String state = NetUtils.loginOfGet(userName, password);
						
						// 执行任务在主线程中,除handle外
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 就是在主线程中操作
								Toast.makeText(MainActivity.this, state, 0).show();
							}
						});
					}
				}).start();
	}

loginOfGet方法:

public class NetUtils {
/**
	 * 使用get的方式登录
	 * @param userName
	 * @param password
	 * @return 登录的状态
	 */
	public static String loginOfGet(String userName, String password) {
		HttpURLConnection conn = null;
		try {
			String data = "username=" + URLEncoder.encode(userName) + "&password=" + URLEncoder.encode(password);
			URL url = new URL("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);
			conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("GET");		// get或者post必须得全大写
			conn.setConnectTimeout(10000); // 连接的超时时间
			conn.setReadTimeout(5000); // 读数据的超时时间
			
			int responseCode = conn.getResponseCode();
			if(responseCode == 200) {
				InputStream is = conn.getInputStream();
				String state = getStringFromInputStream(is);
				return state;
			} else {
				Log.i(TAG, "访问失败: " + responseCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(conn != null) {
				conn.disconnect();		// 关闭连接
			}
		}
		return null;
	}
	
	/**
	 * 根据流返回一个字符串信息
	 * @param is
	 * @return
	 * @throws IOException 
	 */
	private static String getStringFromInputStream(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		
		while((len = is.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		is.close();
		
		String html = baos.toString();	// 把流中的数据转换成字符串, 采用的编码是: utf-8
		
//		String html = new String(baos.toByteArray(), "GBK");
		
		baos.close();
		return html;
	}
}


展开阅读全文

没有更多推荐了,返回首页