标签:
界面代码:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/et_ip" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入IP地址" android:inputType="text" /> <EditText android:id="@+id/et_uesrname" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入用户名" android:text="张三" android:inputType="text" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:inputType="textPassword" /> <Button android:id="@+id/bt_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get方式提交" /> <Button android:id="@+id/bt_post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Post方式提交" /> <Button android:id="@+id/bt_client_get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="httpclient_get方式提交" /> <Button android:id="@+id/bt_client_post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="httpclient_post方式提交" /> </LinearLayout>
服务器端代码:
如果是用Get方法提交数据,直接用java代码块就好,如果使用Post方法提交数据,则需要再加上login.jsp
Get方法提交数据,可以在url中看到提交数据的信息,不安全,且数据长度受限。
Post方法提交数据,是将数据信息写到包头里面,较为安全,且长度不受限。
java代码块:
package com.example.test; import java.io.IOException; /** * Servlet implementation class MyTest */ public class MyTest extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyTest() { 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"); System.out.println("username:" + new String(username.getBytes("iso-8859-1"), "utf-8")); // System.out.println("username:" + username); System.out.println("password:" + password); if("张三".equals(new String(username.getBytes("iso-8859-1"), "utf-8")) && "1234".equals(password)){ response.getOutputStream().write("登陆成功".getBytes()); } else{ response.getOutputStream().write("登陆失败".getBytes()); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
login.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=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="MyTest" method="post"> 用户名:<input name="username" type="text"> <br> 密码:<input name="password" type="password"> <br> <input name="submit" type="submit"> </form> </body> </html>
客户端代码:
//要添加INTERNET权限
package com.example.serviceclient; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.graphics.Region.Op; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * @author kui.zhang * */ /** * @author kui.zhang * */ /** * @author kui.zhang * */ public class MainActivity extends Activity implements OnClickListener { private EditText et_username; private EditText et_password; private EditText et_ip; private Button bt_post; private Button bt_get; private Button bt_client_get; private Button bt_client_post; private String path; private String str1; private String ip; private String username; private String password; // private HttpClient httpclient; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ Toast.makeText(MainActivity.this, str1, 0).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //my code below et_username = (EditText)findViewById(R.id.et_uesrname); et_password = (EditText)findViewById(R.id.et_password); et_ip = (EditText)findViewById(R.id.et_ip); bt_get = (Button)findViewById(R.id.bt_get); bt_post = (Button)findViewById(R.id.bt_post); bt_client_get = (Button)findViewById(R.id.bt_client_get); bt_client_post = (Button)findViewById(R.id.bt_client_post); bt_get.setOnClickListener(this); //启动按键监听器 bt_post.setOnClickListener(this); bt_client_get.setOnClickListener(this); bt_client_post.setOnClickListener(this); } @Override public void onClick(View v) { ip = et_ip.getText().toString().trim(); username = et_username.getText().toString().trim(); password = et_password.getText().toString().trim(); switch(v.getId()){ case R.id.bt_get: //拼装路径 try { path = "http://" + ip + ":8080/test/MyTest?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //开启子线程 new Thread(){ public void run(){ try { str1 = readInputStreamByGet(path); } catch (Exception e) { e.printStackTrace(); str1 = "GET网络超时"; } handler.sendEmptyMessage(2); } }.start(); break; case R.id.bt_post: //post路径不用添加username和password,这些内容写在包头里 path = "http://" + ip + ":8080/test/MyTest"; //开启子线程 new Thread(){ public void run(){ try { str1 = readInputStreamByPost(path); } catch (Exception e) { e.printStackTrace(); str1 ="POST网络超时"; } handler.sendEmptyMessage(1); } }.start(); break; case R.id.bt_client_get: //设置path try { path = "http://" + ip + ":8080/test/MyTest?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8"); } catch (Exception e) { e.printStackTrace(); } //开启子线程 new Thread(){ public void run(){ try { str1 = httpClientByGet(path); } catch (Exception e) { e.printStackTrace(); str1 = "CLIENT_GET网络超时"; } handler.sendEmptyMessage(1); } }.start(); break; case R.id.bt_client_post: //设置path path = "http://" + ip + ":8080/test/MyTest"; //开启子线程 new Thread(){ public void run(){ try { str1 = httpClientPost(path); } catch (Exception e) { e.printStackTrace(); str1 = "CLIENT_POST网络超时"; } handler.sendEmptyMessage(1); } }.start(); break; } //清理 } /** * @实现Get方法提交数据 * @return str=服务器返回输入流的字符串形式 * @throws Exception */ public String readInputStreamByGet(String path) throws Exception{ URL url = new URL(path); //生成URL HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5*1000); conn.setRequestMethod("GET"); InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bop = new ByteArrayOutputStream(); while((len = is.read(buffer)) != -1){ bop.write(buffer, 0, len); } bop.close(); is.close(); String str = new String(bop.toByteArray(), "gbk"); //将服务器返回信息用gbk方式编码 return str; } /** * @实现Post方法提交数据 * @return * @throws Exception */ public String readInputStreamByPost(String path) throws Exception{ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5*1000); conn.setRequestMethod("POST"); String data = "username=" + URLEncoder.encode(username, "utf-8") + "&password=" + URLEncoder.encode(password, "utf-8"); //post特殊定义参数 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length()+""); conn.setDoOutput(true); OutputStream op = conn.getOutputStream(); op.write(data.getBytes()); //获得返回输入流 InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bop = new ByteArrayOutputStream(); while((len = is.read(buffer)) != -1){ bop.write(buffer, 0, len); } op.close(); bop.close(); is.close(); String str = new String(bop.toByteArray(), "gbk"); //将服务器返回信息用gbk方式编码 return str; } /** * @实现通过httpclient这个API来用Get方式提交数据 * @return * @throws Exception */ public String httpClientByGet(String path) throws Exception{ //打开浏览器 HttpClient httpclient = new DefaultHttpClient(); //输入地址 HttpGet httpget = new HttpGet(path); //按回车 HttpResponse response = httpclient.execute(httpget); int code = response.getStatusLine().getStatusCode(); if(code == 200){ InputStream is = response.getEntity().getContent(); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bop = new ByteArrayOutputStream(); while((len = is.read(buffer)) != -1){ bop.write(buffer, 0, len); } is.close(); bop.close(); String str = new String(bop.toByteArray(), "gbk"); return str; } else{ return "返回数据异常"; } } /** * @实现通过httpclient这个API来用Post方式提交数据 * @return * @throws Exception */ public String httpClientPost(String path) throws Exception{ //打开浏览器 HttpClient httpclient = new DefaultHttpClient(); //输入地址 HttpPost httppost = new HttpPost(path); //指定要提交数据的实体 List<NameValuePair> paramaters = new ArrayList<NameValuePair>(); paramaters.add(new BasicNameValuePair("username", username)); paramaters.add(new BasicNameValuePair("password", password)); httppost.setEntity(new UrlEncodedFormEntity(paramaters, "utf-8")); //敲回车 HttpResponse response = httpclient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if(code == 200){ InputStream is = response.getEntity().getContent(); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bop = new ByteArrayOutputStream(); while((len = is.read(buffer)) != -1){ bop.write(buffer, 0, len); } is.close(); bop.close(); String str = new String(bop.toByteArray(), "gbk"); return str; } else{ return "返回数据异常"; } } }
程序实现:
1、通过EditText框动态输入服务器IP
2、支持中文账号
标签:
原文地址:http://www.cnblogs.com/qingriye/p/4786643.html