HTTP协议下Android web应用GET和POST请求方法的请求、响应、传参

原创 2015年11月18日 23:30:09

一、Eclipse创建Dynamic Web Project工程

1、File——new File——写入工程名——Target runtime下面选折Apache tomcat v8.0 并点选右边New Runtime...按钮将你解压tomcat导入,tomcat下有需要用到的第三方工具包servlet
2、点击next——并在Content directory下面的单选框打勾,是为了Web-INF下创建web.xml 用于注册映射相关的Java服务类
3、在WEB-INF下面创建个classes文件夹,单击项目名我这里是LoginTest下拉菜单中点选Properties,在弹出的对话框左边点选Java Build Path 在对话框右边第一栏Source最下面的Default output folder 下的输入框将你创建WEB-INF/classes的path路径写入输入框后,(WEB-INF/classes的路径怎么获取了,点击classes右键下拉菜单Properties弹出对话框将path路径复制,第一个“/”需去掉),中点击finish
这样一个Web项目框架就建好了

当然你也可以手动创建Web工程框架,WEB-INF以及其下web.xml文件这个必须有,同时要引入一个servlet-api.jar第三方包,找不到可以到tomcat的lib目录下去找

二、接下来写服务器端Servlet小应用服务类

1、src下建个包并新建一个类继承于HttpServlet
写出你需要请求响应方法"doGet()"或者"doPost()"的方法,写出相应的逻辑代码:具体代码如下

<span style="font-size:14px;">import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/**指明发送给接收者的实体正文的媒体类型和编码方式*/
		resp.setContentType("text/html;charset=utf-8"); // 解决响应请求中文乱码

		String userName = req.getParameter("user");
		String passWord = req.getParameter("psw");
		System.out.println("doGet userName :"+userName+ " passWord :"+passWord);
		
		/**乱码解决方法一*/
//		String user_Name = new String(userName.getBytes("ISO-8859-1"),"UTF-8");
//		System.out.println("doGet user_Name :"+user_Name+ " passWord :"+passWord);
		
		
		PrintWriter writer = resp.getWriter();
		
		if(userName.equals("admin")){
			writer.print("<html><body><h1>"+userName+"登录成功 </h1></body></html>");
		}else{
			writer.print("<html><body><h1>"+userName+"登录失败 </h1></body></html>");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("doPost >>>>>");
		doGet(req, resp);
		
	}
	
}</span>


<span style="font-size:14px;">import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PrintServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.write("请求成功!");
		
	}
}</span>



2、并在web.xml文件中写出映射查找关系,具体代码如下
<span style="font-size:14px;"><?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"> 
    
    <servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>com.scxh.java1503.LoginServlet</servlet-class>
    </servlet>
    
    <servlet>
      <servlet-name>PrintServlet</servlet-name>
      <servlet-class>com.scxh.java1503.PrintServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>PrintServlet</servlet-name>
        <url-pattern>/print</url-pattern>
    </servlet-mapping>
</web-app></span>



3、在tomcat解压包中找到conf文件夹找到server.xml文件打开,在<Host></Host>之间假如这段代码
<Context path="/app" docBase="F:\WORK\Developer\WORKSPACE\androidExercise\LoginTest\Login"/>
path自定义取名,docBase是指WEB-INF的上级目录绝对路径,这样映射到webapps/Root/目录下了,而不需要没修改就得复制粘贴到该目下,当然最终修改完成还是需要复制粘贴到该目下,这样做只是为了调试方便。
这样服务端的所有准备工作映射关系就准备完毕


三、Android客户端请求服务端程序代码

1、建xml布局
2、activty类实现点击事件注意监听注册,网络连接,当然需要注意网络耗时操作要在子线程中或异步任务AsyncTask中去完成,请求的URL地址不能写错否则报错
具体代码如下
分别实现请求链接
GET请求方法
Post请求方法

<span style="font-size:14px;">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.scxh.android1503.R;
import com.scxh.android1503.util.Logs;

public class HttpConnectActivity extends Activity implements OnClickListener{
	private Button mConnectBtn,mGetConnetBtn,mPostConnetBtn;
	private TextView mShowMessageTxt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http_connect_layout);
		
		mConnectBtn = (Button) findViewById(R.id.http_connect_btn);
		mShowMessageTxt = (TextView) findViewById(R.id.http_show_message_txt);
		mGetConnetBtn = (Button) findViewById(R.id.http_connect_get_btn);
		mPostConnetBtn = (Button) findViewById(R.id.http_connect_post_btn);
		mConnectBtn.setOnClickListener(this);
		mGetConnetBtn.setOnClickListener(this);
		mPostConnetBtn.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		/**建立网络连接*/
		case R.id.http_connect_btn:
			String httpUrl = "http://192.168.1.156/app/print";
			/**异步类解决网络操作不能在主线程*/
			new AsyncTask<String, Void, String>(){
				@Override
				protected String doInBackground(String... params) {
					String httpUrl = params[0];
					try {
						URL url = new URL(httpUrl);
						HttpURLConnection connect = (HttpURLConnection) url.openConnection();
						connect.setRequestMethod("GET");
						connect.connect();
						
						String str = "";
						int statusCode = connect.getResponseCode();
						Logs.v("statusCode  :"+statusCode);
						if(statusCode == 200){
							str = readStr(connect.getInputStream());
						}
						return str;
						
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
					
				}
				protected void onPostExecute(String result) {
					mShowMessageTxt.setText(result);
				}
			}.execute(httpUrl);
			
			break;
			
		case R.id.http_connect_get_btn:
			/**GET请求方法*/
			httpUrl = "http://192.168.1.156/app/login";  ////http://192.168.1.156/app/login?user=xiaoming&psw=abcd"
			
			String userName = "张三";
			try {
				userName = URLEncoder.encode(userName, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			httpUrl = httpUrl + "?user="+userName+"&psw=abcd&sex=男";
			Logs.v("httpUrl :"+httpUrl);
			/**异步类解决网络操作不能在主线程*/
			new AsyncTask<String, Void, String>(){
				@Override
				protected String doInBackground(String... params) {
					String httpUrl = params[0];
					try {
						URL url = new URL(httpUrl);
						HttpURLConnection connect = (HttpURLConnection) url.openConnection();
						connect.setRequestMethod("GET");
						connect.connect();
						
						String str = readStr(connect.getInputStream());
						return str;
						
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
					
				}
				protected void onPostExecute(String result) {
					mShowMessageTxt.setText(result);
				}
			}.execute(httpUrl);
			
			
			break;
		case R.id.http_connect_post_btn:
			/**POST请求方法*/
			httpUrl = "http://192.168.1.156/app/login";
			/**异步类解决网络操作不能在主线程*/
			new AsyncTask<String, Void, String>(){
				@Override
				protected String doInBackground(String... params) {
					Logs.v("doInBackground >>>>>");
					String httpUrl = params[0];
					try {
						URL url = new URL(httpUrl);
						HttpURLConnection connect = (HttpURLConnection) url.openConnection();
						connect.setRequestMethod("POST");
						connect.connect();
						
						OutputStream os = connect.getOutputStream();
						PrintWriter writer = new PrintWriter(os);
						writer.print("user=张三&psw=123456");
						writer.flush();
						
						String str = readStr(connect.getInputStream());
						
						connect.disconnect();
						return str;
						
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
					
				}
				protected void onPostExecute(String result) {
					mShowMessageTxt.setText(result);
				}
			}.execute(httpUrl);
			break;
		}
	}
	/**
	 * 从输入流读数据
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public String readStr(InputStream is) throws IOException{
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		StringBuilder sb = new StringBuilder();
		String line;
		while((line=reader.readLine()) != null){
			sb.append(line);
		}
		reader.close();
		is.close();
		return sb.toString();
	}
	
	
	public String getHttpConnect(String httpUrl){
		try {
			/**Get请求传参方式*/
			httpUrl = httpUrl +"?user=admin&psw=abcd";  //http://192.168.1.156/app/login?user=xiaoming&psw=abcd"
			URL url = new URL(httpUrl);  //统一资源定位符
			HttpURLConnection connet = (HttpURLConnection) url.openConnection();  //打开Http连接
			connet.setRequestMethod("GET");   //设置 http请求方式
			connet.setConnectTimeout(15000);  //设置http连接超时时间
			connet.setReadTimeout(10000);     //设置读数据超时时间
			connet.connect();                 //建立连接
			
			/**post传参实现方式  :
			 * 向字节输出流中写数据  */
			/*OutputStream os = connet.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			pw.print("user=xiaoming&psw=abcd");
			pw.flush();*/
			
			InputStream is = connet.getInputStream();  //得到字节输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); //得到字符输入缓冲流
			
			/**从字符输入缓冲流中一行一行读取数据
			 * 添加到StringBuilder */
			String line;
			StringBuilder sb = new StringBuilder();
			while((line = reader.readLine())!=null){
				sb.append(line);
			}
			
			return sb.toString();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	/**Apache建立连接的方法*/
	public void httpClientConnet(){
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet("http://192.168.1.156/app/login?user=xiaoming&psw=abcd");
		try {
			HttpResponse response = client.execute(request);
			InputStream is = response.getEntity().getContent();
			
			//String str = readStr(is);
			String str = EntityUtils.toString(response.getEntity());
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}</span>



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

java实现的利用HTTP协议原理实现的GET/POST请求的web服务器

1.HTTP协议原理 (1)连接 (2)请求 (3)应答 (4)关闭连接 2.为了测试不同的请求,写了两个html文件。 get.html Documen...

jmeter传参二:get与post请求参数传递方法

得到开发提供的接口文档后,就可以开始写脚本了,如: 1. get请求的入参是json格式的 摘要: 利用httpClient调用接口,成功返回信息 接口地址: (RESTFUL...
  • hw1932
  • hw1932
  • 2017-02-27 21:15
  • 3305

Android开发入门之通过GET和POST方式提交参数给web应用

依然是上一个应用 服务器端: 新建一个名为ManagerServlet的Servlet: package cn.leigo.servlet; import java.io.IOExcept...

Android 网络通信之通过GET和POST方式提交参数给web应用

一。Activity代码 package com.example.http;   import java.util.HashMap; import java.util.Map; import...

HTTP协议中POST、GET、HEAD、PUT等请求方法及相应值得含义

HTTP协议中POST、GET、HEAD、PUT等请求方法及相应值得含义请求方法是请求一定的Web页面的程序或用于特定的URL。可选用下列几种:GET: 请求指定的页面信息,并返回实体主体。HEAD:...

HTTP协议的几种请求方法(get/post 差别)17.2.15日更新

get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEA...

HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误

原文地址:点击打开链接 HTTP协议中POST、GET、HEAD、PUT等请求方法以及一些常见错误     请求方法是请求一定的Web页面的程序或用于特定的URL。可选用下列几种: GE...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)