标签:put client utils orm tps and 数据流 new void
1.模仿登入页面显示(使用传统方式是面向过程的)
使用Apache公司提供的HttpClient API是面向对象的
(文章底部含有源码的连接,包括了使用async框架)
(解决中文乱码的问题。主要是对中文的数据进行URL编码)
android手机默认的编码是UTF-8
2.手机截图Demo
3.server截图
代码例如以下:
server端的代码:
//測试 android设备登入 public class Login extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); //对数据进行编码,解决乱码问题 username = new String(username.getBytes("ISO-8859-1"),"UTF-8"); System.out.println("username--:"+username+"---password:"+password); if(username.equals("admin") && password.equals("123")){ response.getOutputStream().write("登入成功".getBytes("UTF-8")); }else{ response.getOutputStream().write("登入失败".getBytes("UTF-8")); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("UTF-8"); doGet(request, response); } }
Androidclient
布局文件的部分:
//測试 android设备登入 public class Login extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); //对数据进行编码,解决乱码问题 username = new String(username.getBytes("ISO-8859-1"),"UTF-8"); System.out.println("username--:"+username+"---password:"+password); if(username.equals("admin") && password.equals("123")){ response.getOutputStream().write("登入成功".getBytes("UTF-8")); }else{ response.getOutputStream().write("登入失败".getBytes("UTF-8")); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("UTF-8"); doGet(request, response); } }
Activity代码部分:
(注意:android4.0之后訪问网络必须开子线程进行訪问,而且涉及到权限。记得加上訪问网络的权限
以下的代码中,我写入get和post两种方式的线程请求。。
。。。。。
。。。
。。。慢慢体会
)
public class MainActivity extends AppCompatActivity { private static final int SUCCESS = 0; private static final int FAILE = 1; private static final int NET_ERROR = 3; private static final String TAG = "MainActivity"; EditText et_username; EditText et_password; TextView show_result; String username; String password; final String path = "http://188.188.7.85/Android_Server/Login"; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case SUCCESS: String data = (String) msg.obj; show_result.setText(data); break; case FAILE: Toast.makeText(MainActivity.this, "连接server失败", Toast.LENGTH_SHORT).show(); break; case NET_ERROR: Toast.makeText(MainActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show(); break; default: break; } } }; @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); show_result = (TextView) findViewById(R.id.show_result); username = et_username.getText().toString().trim(); password = et_password.getText().toString().trim(); } public void login(View view) { username = et_username.getText().toString().trim(); password = et_password.getText().toString().trim(); if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { Toast.makeText(this, "username与password不能为空", Toast.LENGTH_SHORT).show(); return; } //使用传统get方式的请求server // new Thread_get().start(); //使用传统的post方式请求server new Thread_post().start(); } //传统的post方式请求server端 class Thread_post extends Thread { @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //1.设置请求方式 conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); //设置连接的超时事件是5秒 //2.组合数据,一定要将数据进行URL编码 String commitData = "username="+URLEncoder.encode(username,"UTF-8")+"&password="+URLEncoder.encode(password,"UTF-8"); // 3. 指定content-type -实际上就是指定传输的数据类型 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //4.指定content-length Content-Length: 数据的长度 conn.setRequestProperty("Content-Length", commitData.length() + ""); //5.打开输出流。告诉server,我要写数据了 conn.setDoOutput(true); //6.開始写数据 OutputStream os = conn.getOutputStream(); os.write(commitData.getBytes()); // os.close(); int code = conn.getResponseCode(); //获取返回的成功代码 Log.i(TAG, "code:---" + code); if (code == 200) { //表示连接server成功返回信息 String data = ServerTools.getInfo(conn.getInputStream()); Log.i(TAG, "data:---" + data); //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = SUCCESS; ms.obj = data; handler.sendMessage(ms); } else { //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = FAILE; handler.sendMessage(ms); } } catch (Exception e) { //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = NET_ERROR; handler.sendMessage(ms); e.printStackTrace(); } } } //传统的get方式请求server端 class Thread_get extends Thread { @Override public void run() { try { String getPath = path + "?username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL(getPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); //设置连接的超时事件是5秒 int code = conn.getResponseCode(); //获取返回的成功代码 Log.i(TAG, "code:---" + code); ; if (code == 200) { //表示连接server成功返回信息 String data = ServerTools.getInfo(conn.getInputStream()); Log.i(TAG, "data:---" + data); //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = SUCCESS; ms.obj = data; handler.sendMessage(ms); } else { //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = FAILE; handler.sendMessage(ms); } } catch (Exception e) { //使用消息处理机制,将数据传递给主线程 Message ms = new Message(); ms.what = NET_ERROR; handler.sendMessage(ms); e.printStackTrace(); } } } }
工具类:
public class ServerTools { //从服务端获取流数据进行转化成文本文件 public static String getInfo(InputStream in) { //将数据流写在内存中 ByteArrayOutputStream raf = new ByteArrayOutputStream(); String data = null; try{ byte[] bt = new byte[1024]; int len =0 ; while((len = in.read(bt)) != -1){ raf.write(bt,0,len); } data = raf.toString(); }catch (Exception e){ e.printStackTrace(); } return data; } }
Android的源码已经放在github中:
传统方式Demo地址:https://github.com/momxmo/HTTP_get_post
Apache提供的HttpClient API面向对象的方式Demo:https://github.com/momxmo/HttpClient_get_post
使用async-http-master流行框架进行http请求:https://github.com/momxmo/Http_android-async-http-master_Demo
Android传统HTTP请求get----post方式提交数据(包括乱码问题)
标签:put client utils orm tps and 数据流 new void
原文地址:http://www.cnblogs.com/zhchoutai/p/6937654.html