java後臺發起請求方式
使用HttpClient:
NameValuePair nameValuePair1 = newBasicNameValuePair("name", "yang");
NameValuePair nameValuePair2 = newBasicNameValuePair("pwd","123123");
List nameValuePairs = new ArrayList();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
String validateURL = "http://10.0.2.2:8080/testhttp1/TestServlet
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,5000); //設定連線超時為5秒
HttpClient client = newDefaultHttpClient(httpParams); //生成一個http客戶端傳送請求物件
HttpPost httpPost = newHttpPost(urlString); //設定請求方式
if (nameValuePairs!=null&& nameValuePairs.size()!=0){
//把鍵值對進行編碼操作並放入HttpEntity物件中
httpPost.setEntity(newUrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
}
HttpResponse httpResponse =client.execute(httpPost); // 傳送請求並等待響應
//判斷網路連線是否成功
if (httpResponse.getStatusLine().getStatusCode()!= 200) {
System.out.println("網路錯誤異常!!!!");
returnfalse;
}
HttpEntity entity = httpResponse.getEntity(); // 獲取響應裡面的內容
inputStream = entity.getContent(); //得到服務氣端發回的響應的內容(都在一個流裡面)
// 得到服務氣端發回的響應的內容(都在一個字串裡面)
// String strResult =EntityUtils.toString(entity);
}catch (Exception e) {
System.out.println("這是異常!");
}
使用HttpURLConnection:
try {
URL url = new URL(validateUrl); //建立URL物件
//返回一個URLConnection物件,它表示到URL所引用的遠端物件的連線
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000); //設定連線超時為5秒
conn.setRequestMethod("GET"); //設定請求方式
conn.connect(); //建立到遠端物件的實際連線
//返回開啟連線讀取的輸入流
DataInputStreamdis = newDataInputStream(conn.getInputStream());
//判斷是否正常響應資料
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("網路錯誤異常!!!!");
return false;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("這是異常!");
} finally {
if (conn !=null) {
conn.disconnect(); //中斷連線
}
}