运用URLconnection向服务器发送请求
u任务描述
Ø编写Servlet服务器接受客户端发来的请求,根据请求的方式(get,post),将对应的字符串返回给服务器显示到TextView中。
Get请求返回字符串: The request method : get
Post请求返回字符串: The request method : post
Ø编写URLconnection向服务器发送请求并告诉服务器请求的方式。
关联知识点
ØURLconnection与服务器建立连接方法
Ø通过URLconnection向服务器发送信息
Ø从服务器接受返回数据的方法
实现步骤
Ø启动线程,根据URL获取URLConnection并建立连接,设置请求的属性,并通过输出流获取服务器发送回来的信息。使用handler更新TextView中字符串
服务器端代码
public class TestServer extends HttpServlet { private static final long serialVersionUID = 1L; /** * 当用户的请求为GET请求,从参数中获取名为method的值,并告诉用户此次连接为get连接 */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取method参数对应的值 String param = request.getParameter("method"); // 获得输出流,准备做写入操作 PrintWriter writer = new PrintWriter(response.getOutputStream()); // 如果method参数的值是get,则写入提示,告诉用户这次是get请求 if (param != null && param.equals("get")) { writer.println("The request method : get"); writer.flush(); } // 强制刷新缓存 if (writer != null) { writer.flush(); writer.close(); } } /** * 当用户的请求为POST请求,从参数中获取名为method的值,并告诉用户此次连接为post连接 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取method参数对应的值 String param = request.getParameter("method"); // 获得输出流,准备做写入操作 PrintWriter writer = new PrintWriter(response.getOutputStream()); // 如果method参数的值是get,则写入提示,告诉用户这次是get请求 if (param != null && param.equals("post")) { writer.write("The request method : post \n"); } // 强制刷新缓存 if (writer != null) { writer.flush(); writer.close(); } } }
android客户端代码:
public class MainActivity extends Activity { TextView tv = null; Button btnGet = null; Button btnPost = null; //用来处理刷新UI控件 Handler myHandler = null; //服务器的地址 URL url = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textView1); btnGet = (Button) findViewById(R.id.button1); btnPost = (Button) findViewById(R.id.button2); myHandler = new Handler() { @Override public void handleMessage(Message msg) { //当handler收到消息后,便会根据消息中的obj值更新TextView tv.setText(msg.obj.toString()); } }; btnGet.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //启用线程处理网络操作 new Thread() { @Override public void run() { try { //创建URL,此处我们使用GET请求,所以将尾部method=get是我们向服务器发送的参数。 url = new URL( "http://10.0.2.2/Chapter3ExerciseServer1/TestServer?method=get"); //建立连接 URLConnection conn = url.openConnection(); //设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); //获取输入流,准备从服务器读取返回的信息 DataInputStream dis = new DataInputStream(conn .getInputStream()); //处理动态数组 ByteArrayOutputStream bos = new ByteArrayOutputStream(); //缓冲区 byte[] buffer = new byte[1024]; while (dis.read(buffer) > 0) { //将读取的缓冲数组写入数组输出流以便于创建动态数组 bos.write(buffer); } //将服务器返回的数据转换成String类型 String context = new String(bos.toByteArray()) .trim(); //关闭流 dis.close(); bos.close(); //创建消息,发送给handler Message msg = Message.obtain(); //消息的obj为此次获取的数据 msg.obj = context; myHandler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }); btnPost.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { try { //创建URL,此处我们使用POST请求。 url = new URL( "http://10.0.2.2/Chapter3ExerciseServer1/TestServer"); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); //告诉服务器,这次的请求为POST请求 conn.setDoOutput(true); conn.setDoInput(true); //获取输出流,将我们需要传递的参数输出给服务器 DataOutputStream dos = new DataOutputStream(conn .getOutputStream()); //传递的参数 String param = new String("method=post"); //写入并刷新 dos.write(param.getBytes()); dos.flush(); //获取服务器的返回信息 DataInputStream dis = new DataInputStream(conn .getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (dis.read(buffer) > 0) { bos.write(buffer); buffer = new byte[1024]; } String context = new String(bos.toByteArray()) .trim(); Log.i("context", context); dis.close(); bos.close(); dos.close(); Message msg = Message.obtain(); msg.obj = context; myHandler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }