android中Post方式发送HTTP请求

Post方式比Get方式要复杂一点,因为该方式需要将请求的参数放在http请求的正文中,所以需要构造请求体。

步骤:

1.构造URL

URL url = new URL(PATH);

2.设置连接
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(3000);
      connection.setDoInput(true);//表示从服务器获取数据
      connection.setDoOutput(true);//表示向服务器写数据
      //获得上传信息的字节大小以及长度
     
      connection.setRequestMethod("POST");
      //是否使用缓存
      connection.setUseCaches(false);
      //表示设置请求体的类型是文本类型
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      
      connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
      connection.connect();   
3.写入请求正文

Map<String, String> params = new HashMap<String, String>();
params.put("username", "lili");
params.put("password", "123");

StringBuffer buffer = new StringBuffer();
try {//把请求的主体写入正文!!
 if(params != null&&!params.isEmpty()){
//迭代器
  for(Map.Entry<String, String> entry : params.entrySet()){
  buffer.append(entry.getKey()).append("=").
  append(URLEncoder.encode(entry.getValue(),encode)).
  append("&");
  }
}
//   System.out.println(buffer.toString());
  //删除最后一个字符&,多了一个;主体设置完毕
  buffer.deleteCharAt(buffer.length()-1);
  byte[] mydata = buffer.toString().getBytes(); 

//获得输出流,向服务器输出数据
      OutputStream outputStream = connection.getOutputStream();
           outputStream.write(mydata,0,mydata.length);

4.读取返回数据,关闭连接

//通常叫做内存流,写在内存中的
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if(inputStream != null){
try {
while((len = inputStream.read(data))!=-1){
data.toString();

outputStream.write(data, 0, len);
}
//result是在服务器端设置的doPost函数中的
result = new String(outputStream.toByteArray(),encode);
outputStream.flush();

下面上代码:一个简单的Demo访问一个自建的Servlet

package com.http.post;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

	private static String PATH = "http://172.24.87.47:8088/myhttp/servlet/LoginAction";
	private static URL url;
	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	static{
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @param params 填写的url的参数
	 * @param encode 字节编码
	 * @return
	 */
	public static String sendPostMessage(Map<String, String> params,String encode){
		StringBuffer buffer = new StringBuffer();
		try {//把请求的主体写入正文!!
			 if(params != null&&!params.isEmpty()){
				//迭代器
			  for(Map.Entry<String, String> entry : params.entrySet()){
				  buffer.append(entry.getKey()).append("=").
				  append(URLEncoder.encode(entry.getValue(),encode)).
				  append("&");
			  }
			}
//			  System.out.println(buffer.toString());
			  //删除最后一个字符&,多了一个;主体设置完毕
			  buffer.deleteCharAt(buffer.length()-1);
			  byte[] mydata = buffer.toString().getBytes(); 
			  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		      connection.setConnectTimeout(3000);
		      connection.setDoInput(true);//表示从服务器获取数据
		      connection.setDoOutput(true);//表示向服务器写数据
		      //获得上传信息的字节大小以及长度
		     
		      connection.setRequestMethod("POST");
		      //是否使用缓存
		      connection.setUseCaches(false);
		      //表示设置请求体的类型是文本类型
		      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		      
		      connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
		      connection.connect();   //连接,不写也可以。。??有待了解
		   
			  //获得输出流,向服务器输出数据
		      OutputStream outputStream = connection.getOutputStream();
		           outputStream.write(mydata,0,mydata.length);
		           //获得服务器响应的结果和状态码
		      int responseCode = connection.getResponseCode(); 
		      if(responseCode == HttpURLConnection.HTTP_OK){
		    	 return changeInputeStream(connection.getInputStream(),encode);
		    	  
		      }
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
   /**
    * 将一个输入流转换成字符串
    * @param inputStream
    * @param encode
    * @return
    */
	private static String changeInputeStream(InputStream inputStream,String encode) {
        //通常叫做内存流,写在内存中的
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if(inputStream != null){
			try {
				while((len = inputStream.read(data))!=-1){
					data.toString();
					
					outputStream.write(data, 0, len);
				}
				//result是在服务器端设置的doPost函数中的
				result = new String(outputStream.toByteArray(),encode);
				outputStream.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] arsg){
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "lili");
		params.put("password", "123");
		String result = sendPostMessage(params,"utf-8");
		System.out.println("result->"+result);
	}
}
//下边是服务端的Servlet代码:

package com.login.manager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 LoginAction extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public LoginAction() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		System.out.println("username:"+username);
		String pswd = request.getParameter("password");
		System.out.println("password:"+pswd);
		if(username.equals("张三")&&pswd.equals("123")){
			//表示服务器端返回的结果
			out.print("login is success!!!!");
		}else{
			out.print("login is fail!!!");
		}
		//通常叫做内存流,写在内存中的
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int temp=0;
		byte[] data = new byte[1024];
		InputStream inputStream = request.getInputStream();
		while((temp=inputStream.read(data))!=-1){
			outputStream.write(data, 0, temp);
		    }
		String result = new String(outputStream.toByteArray(),"utf-8");
		System.out.println("输入的内容是:"+result);  //空的??ServletInputStream??
	
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

结果如下:

客户端的:                                                                                                   这是服务端的:

       

可以看到参数已经传过去啦,配置成功。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值