AndroidはHTTPプロトコルに向かってpost要求を送信する。
1343 ワード
/**
* 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;
}