android 和服务器通信,通常有post 和get 方法。这里写了一个小案例,模拟手机注册账户,把name和age信息提交到服务器。由于在UI线程不能做联网操作,我们自定义一个线程类HttpThread继承Thread
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方法结果一样。
代码下载