zoukankan      html  css  js  c++  java
  • Android面向HTTP协议发送post请求

    /**
    	 * 採用post请求的方式
    	 * 
    	 * @param username
    	 * @param password
    	 * @return null表示求得的路径有问题,text返回请求得到的数据
    	 */
    	public static String postRequest(String username, String password) {
    		try {
    			String path = "http://172.22.64.156:8080/0001AndroidWebService/LoginServlet";
    			URL url = new URL(path);
    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    			conn.setReadTimeout(500);
    			conn.setRequestMethod("POST");
    			// username=donghongyu&&password=123
    			// 准备要传输的数据
    			String data = "username=" + URLEncoder.encode(username)
    					+ "&password=" + URLEncoder.encode(password);
    			// 设置请求的内容的类型
    			conn.setRequestProperty("Content-Type",
    					"application/x-www-form-urlencoded");
    			conn.setRequestProperty("Content-Length", data.length() + "");
    
    			// 开启向server写入的权限
    			conn.setDefaultUseCaches(true);
    			// 获取http连接的输出流
    			OutputStream os = conn.getOutputStream();
    			// 向server写入数据
    			os.write(data.getBytes());
    
    			int code = conn.getResponseCode();
    			if (code == 200) {
    				// 请求成功
    				InputStream is = conn.getInputStream();
    				String text = StreamUtil.readStream(is);
    				return text;
    			} else {
    				// 请求失败
    				return null;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    

  • 相关阅读:
    商贸通帐套隐藏方法
    固定资产打开提示:上年度数据未结转!
    ZOJ 2432 Greatest Common Increasing Subsequence
    POJ 1080 Human Gene Functions
    POJ 1088 滑雪
    POJ 1141 Brackets Sequence
    POJ 1050 To the Max
    HDOJ 1029 Ignatius and the Princess IV
    POJ 2247 Humble Numbers
    HDOJ 1181 变形课
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5278121.html
Copyright © 2011-2022 走看看