1、使用HttpClient:網絡
NameValuePair username = new BasicNameValuePair("username", "zhangsan");
NameValuePair password = new BasicNameValuePair("password","1qaz2wsx");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(username);
params.add(password);
String validateURL = "http://10.1.1.0:8080/dbconnect/ConnectServlet";編碼
try {url
HttpParams httpParams = new BasicHttpParams();code
HttpConnectionParams.setConnectionTimeout(httpParams,5000); //設置鏈接超時爲5秒orm
HttpClient client = new DefaultHttpClient(httpParams); // 生成一個http客戶端發送請求對象對象
HttpPost httpPost = new HttpPost(urlString); //設定請求方式字符串
if (params!=null && params.size()!=0) {
//把鍵值對進行編碼操做並放入HttpEntity對象中
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
}get
HttpResponse httpResponse = client.execute(httpPost); // 發送請求並等待響應input
// 判斷網絡鏈接是否成功
if (httpResponse.getStatusLine().getStatusCode() != 200) {
System.out.println("網絡錯誤異常!");
}else{it
HttpEntity entity = httpResponse.getEntity(); // 獲取響應裏面的內容
inputStream = entity.getContent(); // 獲得服務氣端發回的響應的內容(都在一個流裏面)
// 獲得服務氣端發回的響應的內容(都在一個字符串裏面)
String strResult = EntityUtils.toString(entity);
System.out.println(strResult);
}
} catch (Exception e) {
e.printStackTrace();
}
2、使用HttpURLConnection:
String validateUrl="http://10.1.1.0:8080/dbconnect/ConnectServlet?username=zhangsan&password=1qaz2wsx";
try {
URL url = new URL(validateUrl); //建立URL對象
//返回一個URLConnection對象,它表示到URL所引用的遠程對象的鏈接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); //設置鏈接超時爲5秒
conn.setRequestMethod("GET"); //設定請求方式
conn.connect(); //創建到遠程對象的實際鏈接
//返回打開鏈接讀取的輸入流
BufferedInputStream dis = new BufferedInputStream(conn.getInputStream());
//判斷是否正常響應數據
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("網絡錯誤異常!");
}else{
//讀取數據流
byte[] contents = new byte[1024];
int byteRead = 0;
String strFileContents;
try {
while((byteRead = dis.read(contents)) != -1){
strFileContents = new String(contents,0,byteRead);
System.out.println(strFileContents);
} catch (IOException e) {
e.printStackTrace();
}
dis.close();
}
} catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); //中斷鏈接 } }