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