Android中的Http通信
2015-09-20 19:14
435 查看
android 和服务器通信,通常有post 和get 方法。这里写了一个小案例,模拟手机注册账户,把name和age信息提交到服务器。由于在UI线程不能做联网操作,我们自定义一个线程类HttpThread继承Thread
线程定义好,看看布局,两个输入框,一个按钮,点击提交
效果是这样的
然后在activity里初始化视图,给按键添加监听:
服务器呢,如果装有tomcat,新建一个dynamic web project,名叫loginServer新建一个login.jsp文件,添加一个表单,测试一下,以备手机端访问使用
,同时新建一个servlet,重写doPost()和doGet()方法。
然后启动服务loginServer,右键,run on server
再然后,运行App,测试
这就成功了,
GET和POST方法结果一样。
代码下载
package com.example.registeractivity; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostThread extends Thread { String url; String name; String age; public PostThread(String url, String name, String age) { super(); this.url = url; this.name = name; this.age = age; } @Override public void run() { // doGet(); doPost(); super.run(); } private void doHttpClientPost() { String urlPostfix = "name="+name+"&age="+age; HttpPost post = new HttpPost(url); HttpClient client = new DefaultHttpClient(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("age", age)); try { post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Log.w("POST", "post OK "+response.toString()); } String content = EntityUtils.toString(entity); Log.w("content:", content); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void doHttpClientGet() { url = url+ "?name="+name+"&age="+age; HttpGet get = new HttpGet(url); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //如果状态为200, HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); System.out.println(content); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //GET方式 private void doGet() { url = url+ "?name="+name+"&age="+age; try { URL httpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000);//設置5秒超時 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("result:"+sb.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //POST方式 private void doPost() { String urlPostfix = "name="+name+"&age="+age; try { URL httpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setReadTimeout(5000);//設置5秒超時 OutputStream out = conn.getOutputStream(); out.write(urlPostfix.getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("result:"+sb.toString()); } catch (Exception e) { e.printStackTrace(); } } }
线程定义好,看看布局,两个输入框,一个按钮,点击提交
<RelativeLayout 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:padding="16dp" tools:context="com.example.registeractivity.MainActivity" > <LinearLayout android:id="@+id/ll1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:gravity="center_vertical" android:orientation="horizontal" > <TextView android:id="@+id/tv_name" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center_vertical" android:text="姓名" /> <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="center_vertical" android:layout_alignParentTop="true" android:layout_toRightOf="@id/tv_name" android:layout_weight="5" android:ems="10" android:hint="请输入姓名" /> </LinearLayout> <LinearLayout android:id="@+id/ll2" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/ll1" android:orientation="horizontal" > <TextView android:text="年龄" android:layout_width="0dp" android:layout_height="match_parent" android:layout_below="@+id/tv_age" android:gravity="center_vertical" android:layout_weight="1" /> <EditText android:id="@+id/et_age" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="center_vertical" android:layout_toRightOf="@id/tv_age" android:layout_weight="5" android:ems="10" android:hint="请输入年龄"/> </LinearLayout> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bt_submit" android:layout_below="@id/ll2" android:layout_alignParentRight="true" android:text="提交" /> </RelativeLayout>
效果是这样的
然后在activity里初始化视图,给按键添加监听:
package com.example.registeractivity; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private EditText mEtName; private EditText mEtAge; private Button mBtSubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } //http://localhost:8080/web/MyServlet?name=laxian&age=2011 private void initView() { mEtName = (EditText) findViewById(R.id.et_name); mEtAge = (EditText) findViewById(R.id.et_age); mBtSubmit = (Button) findViewById(R.id.bt_submit); mBtSubmit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //本机开的服务器,ip地址可以通过dos命令:ipconfig 查看 String url = "http://192.168.31.126:8080/web/MyServlet"; HttpThread thread = new HttpThread(url, mEtName.getText().toString(), mEtAge.getText().toString()); thread.start();; } }); } }
服务器呢,如果装有tomcat,新建一个dynamic web project,名叫loginServer新建一个login.jsp文件,添加一个表单,测试一下,以备手机端访问使用
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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="MyServlet" method="get"> name:<input type="text" name="name"><br> age:<input type="text" name="age"><br> submit:<input type="submit" value="submit"><br> </form> </body> </html>
,同时新建一个servlet,重写doPost()和doGet()方法。
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String age = request.getParameter("age"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("name: "+new String(name.getBytes("iso-8859-1"),"utf-8")+" age: "+age); System.out.println("name: "+new String(name.getBytes("iso-8859-1"),"utf-8")+" age: " +" age: "+age); }
然后启动服务loginServer,右键,run on server
再然后,运行App,测试
这就成功了,
GET和POST方法结果一样。
代码下载
相关文章推荐
- 当打开sql server2008打开,出现报错“评估期已过。有关如何升级的测试版软件的信息请访问,http://www.....”
- 2015北京赛区网络赛模拟题
- flex http请求error#1090XML 分析器失败: 元素格式不正确。
- 2015年ACM北京网络赛 B题 (模拟+枚举题意请原谅我英语不好。。。)
- 程序一启动检查网络,如果没有网络就退出程序
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2015)网络赛A题2015-9-20
- python keras (一个超好用的神经网络框架)的使用以及实例
- 2015 ACM-ICPC 沈阳网络赛总结
- servlet学习---第二天(GenericServlet、HttpServlet开发servler程序)
- 5种服务器网络编程模型讲解
- MITM to crack Https connections
- 网络通讯方式 ------ TCP、UDP
- TCP、UDP练习题 (UDP聊天程序、TCP上传文本文件和图片文件)
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2015)网络赛H题2015-9-20
- linux学习与实战:https://www.shiyanlou.com (不需要你有linux机子, 也不需要安装linux虚拟机)
- TCP状态机
- HTTPS协议和SSL/TLS协议
- 用于解析Json数据的HttpUtils工具类
- HDOJ 5461 Largest Point(沈阳网络赛)
- HDOJ 5455 Fang Fang(字符串)(沈阳网络赛)