当前位置:天才代写 > tutorial > 安卓教程 > Android面向HTTP协议发送post请求

Android面向HTTP协议发送post请求

2021-02-24 12:19 星期三 所属: 安卓教程 浏览:392

/**
	 * 採用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;
	}

 

    关键字:

天才代写-代写联系方式