1、GET方式
其實GET方式說白了,就是拼接字符串。。最後拼成的字符串的格式是: path ? username= ....& password= ......
[java]
public boolean loginByGet(String path, String username , String password) throws Exception{
String url_path = path +"?username=" + URLEncoder.encode(username, "utf-8") + "&password="+password;
URL url = new URL(url_path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
2、POST方式
post方式中,一定要設置以下兩個請求參數
[java]
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length + "");
完整代碼如下:
[java]
public boolean loginByPost(String path,String username , String password) throws Exception{
System.out.println("LoginService的loginByPost()");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
String value = "username=" + username +"&" + "password=" +password;
byte[] entity = value.getBytes();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", entity.length + "");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(entity);
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
3、通過HttpClient以GET方式提交請求
使用HttpClient這個第三方框架以後,我們在編寫代碼的時候就看不到URL、conn之類的。他其實就是對Http協議進行了封裝
[java]
public boolean loginByHttpClientGet(String path,String username , String password) throws Exception{
String value = path + "?username=" + username +"&password=" + password;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(value);
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
return true;
}
return false;
}
4、通過HttpClient以POST方式提交請求
[java]
[java]
public boolean loginByHttpClientPost(String path,String username , String password)throws Exception{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(path);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200){
return true;
}
return false;
}