/*该类演示了四种方法提交数据到服务器,并将服务器解析后的数据以字符串的形式返回*/public class LoginService {/** *  * @param username * @param password * @return */public static String loginByGet(String username,String password){try {//提交数据到服务器//拼装路径String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接conn.setRequestMethod("GET");//设置请求方式为getconn.setConnectTimeout(5000);//设置连接超时时间为5秒int code = conn.getResponseCode();//获得请求码if(code == 200){InputStream is = conn.getInputStream();String text = StreamTools.readInputStream(is);return text;}else{return null;}} catch (Exception e) {e.printStackTrace();}return null;}/** *  * @param username * @param password * @return */public static String loginByPost(String username,String password){try {//提交数据到服务器//拼装路径String path = "http://192.168.1.100/Web/servlet/LoginServlet";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//打开连接conn.setRequestMethod("POST");//设置请求方式为getconn.setConnectTimeout(5000);//设置连接超时时间为5秒//准备数据String data = "username="+ URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8");conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", data.length()+"");//post的方式实际上是浏览器把数据写给了服务器conn.setDoOutput(true);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) {e.printStackTrace();}return null;}/** * 采用httpclient get提交数据 * @param username * @param password * @return */public static String loginByClientGet(String username,String password){try {//1.打开一个浏览器HttpClient client = new DefaultHttpClient();//2.输入地址String path = "http://192.168.1.100/Web/servlet/LoginServlet?username="+ URLEncoder.encode(username)+ "&password="+ URLEncoder.encode(password);HttpGet httpGet = new HttpGet(path);//3.敲回车HttpResponse response = client.execute(httpGet);int code = response.getStatusLine().getStatusCode();if (code == 200) {InputStream is = response.getEntity().getContent();String text = StreamTools.readInputStream(is);return text;} else {return null;}} catch (Exception e) {e.printStackTrace();return null;}}/** * 采用httpclient post提交数据 * @param username * @param password * @return */public static String loginByClientPost(String username,String password){try {//1.打开一个浏览器HttpClient client = new DefaultHttpClient();//2.输入地址String path = "http://192.168.1.100/Web/servlet/LoginServlet";HttpPost httpPost = new HttpPost(path);//指定要提交的数据实体List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("username", username));parameters.add(new BasicNameValuePair("password", password));httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));//3.敲回车HttpResponse response = client.execute(httpPost);int code = response.getStatusLine().getStatusCode();if (code == 200) {InputStream is = response.getEntity().getContent();String text = StreamTools.readInputStream(is);return text;} else {return null;}} catch (Exception e) {e.printStackTrace();return null;}}}

将输入流转换为字符串的工具类StreamTools代码如下:

public class StreamTools {/** * 把输入流的内容转化成字符串 * @param is * @return * @throws IOException  */public static String readInputStream(InputStream is){try {ByteArrayOutputStream stream = new ByteArrayOutputStream();int len = 0;byte[] buffer = new byte[1024];while((len=is.read(buffer))!=-1){stream.write(buffer, 0, len);}is.close();stream.close();byte[] result = stream.toByteArray();//试着解析 result 里面的字符串String temp = new String(result);return temp;} catch (Exception e) {e.printStackTrace();return "获取失败";}}}

在主界面测试是否成功提交的代码如下:

public class MainActivity extends Activity {private EditText et_username;private EditText et_password;@Overrideprotected 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);}public void click1(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() {@Overridepublic void run() {Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();}});}else{runOnUiThread(new Runnable() {@Overridepublic void run() {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.loginByGet(username, password);if(result!=null){runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();}});}else{runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();}});}};}.start();}public void click3(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.loginByClientGet(username, password);if(result!=null){runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();}});}else{runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();}});}};}.start();}public void click4(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.loginByClientPost(username, password);if(result!=null){runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();}});}else{runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "请求失败...", Toast.LENGTH_SHORT).show();}});}};}.start();}public void click5(View view){final String username = et_username.getText().toString().trim();final String password = et_password.getText().toString().trim();AsyncHttpClient client = new AsyncHttpClient();String url = "http://127.0.0.1:80/Web/servlet/LoginServlet";RequestParams params = new RequestParams();params.put("username", username);params.put("password", password);client.post(url, params, new AsyncHttpResponseHandler() {@Overridepublic void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();}@Overridepublic void onFailure(int statusCode, Header[] headers,byte[] responseBody, Throwable error) {Toast.makeText(MainActivity.this, "请求失败..."+new String(responseBody), 0).show();}});}}

其中第五中点击事件是异步请求。

更多相关文章

  1. 分享Android中ExpandableListView控件使用教程
  2. GreenDAO—Android(安卓)ORM框架(一)
  3. android中在androidmanifest.xml设置权限请求
  4. android google 登录流程及遇到的坑
  5. Android(安卓)使用 Batterystats 和 Battery Historian 分析电池
  6. Volley源码解析
  7. 【Android】MVVM架构 RecyclerView加载数据滑动到后面,数据错乱,点
  8. 使用Android(安卓)Camera2 API获取YUV数据
  9. Android性能优化——优化下载以高效地访问网络

随机推荐

  1. Android图像滤镜框架GPUImage使用(二)
  2. Android(安卓)5大布局特点—1
  3. android bluetooth ----BluetoothDevice
  4. Android点击软键盘外的区域,关闭软键盘
  5. Android中WindowManager.LayoutParams类
  6. Flutter吸附效果
  7. Ubuntu Android(安卓)Studio快捷方式创建
  8. activity打开时不自动弹出软键盘
  9. Android(安卓)-- 自定义 View XML属性详
  10. Android使用jsp+sevlet+mysql实现简单的