java實現http協議連線和下載
阿新 • • 發佈:2019-02-05
String currentUrl=“http://www.myWeb.com/login.jsp?userName='Devin'&passWord='mypassword'”; //URL ?後面的內容為HTTP請求的正文URL url = new URL(currentUrl);
HttpURLConnection httpurlconnection = url.openConnection();//下面的設定對應HTTP請求中的訊息報頭
httpurlconnection.setRequestProperty("User-Agent",CommonValues.User_Agent);
httpurlconnection.setRequestProperty("Accept",CommonValues.Accept);
httpurlconnection.setRequestProperty("Accept-Charset",CommonValues.Accept_Charset);
httpurlconnection.setRequestProperty("Accept-Language",CommonValues.Accept_Language);
httpurlconnection.setRequestProperty("Connection",CommonValues.Connection);
httpurlconnection.setRequestProperty("Keep-Alive",CommonValues.Keep_Alive);
httpurlconnection.setConnectTimeout(CommonValues.ConnectionTimeOut);
httpurlconnection.setReadTimeout(CommonValues.ReadTimeOut);
httpurlconnection.connect();
int responsecode = httpurlconnection.getResponseCode();
if(responsecode == HttpURLConnection.HTTP_OK) //對應HTTP響應中狀態行的響應碼{
//操作請求流,這裡對應HTTP響應中的響應正文
}
if (httpurlconnection != null)
{
httpurlconnection.disconnect();
}
HttpURLConnection httpurlconnection = url.openConnection();//下面的設定對應HTTP請求中的訊息報頭
httpurlconnection.setRequestProperty("User-Agent",CommonValues.User_Agent);
httpurlconnection.setRequestProperty("Accept",CommonValues.Accept);
httpurlconnection.setRequestProperty("Accept-Charset",CommonValues.Accept_Charset);
httpurlconnection.setRequestProperty("Accept-Language",CommonValues.Accept_Language);
httpurlconnection.setRequestProperty("Connection",CommonValues.Connection);
httpurlconnection.setRequestProperty("Keep-Alive",CommonValues.Keep_Alive);
httpurlconnection.setConnectTimeout(CommonValues.ConnectionTimeOut);
httpurlconnection.setReadTimeout(CommonValues.ReadTimeOut);
httpurlconnection.connect();
int responsecode = httpurlconnection.getResponseCode();
if(responsecode == HttpURLConnection.HTTP_OK) //對應HTTP響應中狀態行的響應碼{
//操作請求流,這裡對應HTTP響應中的響應正文
}
if (httpurlconnection != null)
{
httpurlconnection.disconnect();
}