java網路程式設計:URLConnection 和HttpURLConnection
阿新 • • 發佈:2019-02-07
URLConnection和HttpURLConnection使用的都是Java.net中的類,屬於標準的java介面。
HttpURLConnection繼承自URLConnection,差別在與HttpURLConnection僅僅針對Http連線。
1) 建立 URL 以及 URLConnection / HttpURLConnection 物件
2) 設定連線引數
3) 連線到伺服器
4) 向伺服器寫資料
5)從伺服器讀取資料
public void urlConnection() { String urltext = ""; try { // 方法一: URL url = new URL(urltext); URLConnection conn = url.openConnection();//取得一個新的連結對指定的URL conn.connect();//本方法不會自動重連 InputStream is = conn.getInputStream(); is.close();//關閉InputStream // 方法二: URL url2 = new URL(urltext); InputStream is2 = url2.openStream(); is2.close();//關閉InputStream //URL物件也提供取得InputStream的方法。URL.openStream()會開啟自動連結,所以不需要執行openConnection //方法三:本方法同一,但是openConnection返回值直接轉為HttpsURLConnection, //這樣可以使用一些Http連線特有的方法,如setRequestMethod URL url3 = new URL(urltext); HttpsURLConnection conn3 =(HttpsURLConnection)url.openConnection(); conn3.setRequestMethod("POST"); //允許Input、Output,不使用Cache conn3.setDoInput(true); conn3.setDoOutput(true); conn3.setUseCaches(false); /* * setRequestProperty */ conn3.setRequestProperty("Connection", "Keep-Alive"); conn3.setRequestProperty("Charset", "UTF-8"); conn3.setRequestProperty("Content-type", "multipart/form-data;boundary=*****"); //在與伺服器連線之前,設定一些網路引數 conn3.setConnectTimeout(10000); conn3.connect(); // 與伺服器互動:向伺服器端寫資料,這裡可以上傳檔案等多個操作 OutputStream outStream = conn3.getOutputStream(); ObjectOutputStream objOutput = new ObjectOutputStream(outStream); objOutput.writeObject(new String("this is a string…")); objOutput.flush(); // 處理資料, 取得響應內容 InputStream is3 = conn.getInputStream(); is3.close();//關閉InputStream } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
常見的Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)下載地址:http://archive.apache.org/dist/httpcomponents/commons-httpclient/3.0/
String LOGIN_ADDRESS = "http://172.0.0.1"; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(LOGIN_ADDRESS); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); method.addParameter("name", "001010058130002"); method.addParameter("user", "150401255562"); method.addParameter("password", "1"); try { // 1:成功 ; 0:失敗 int state = client.executeMethod(method); String flag = method.getResponseBodyAsString(); System.out.println("state:" + state); System.out.println("jsonStr:" + flag); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Apache HttpClient模組是HttpClient 4.0(org.apache.http.*)
HttpClient常用HttpGet和HttpPost這兩個類,分別對應Get方式和Post方式。
無論是使用HttpGet,還是使用HttpPost,都必須通過如下3步來訪問HTTP資源。1.建立HttpGet或HttpPost物件,將要請求的URL通過構造方法傳入HttpGet或HttpPost物件。
2.使用DefaultHttpClient類的execute方法傳送HTTP GET或HTTP POST請求,並返回HttpResponse 物件。
3.通過HttpResponse介面的getEntity方法返回響應資訊,並進行相應的處理。
如果使用HttpPost方法提交HTTP POST請求,則需要使用HttpPost類的setEntity方法設定請求引數。引數則必須用NameValuePair[]陣列儲存。
HttpGet
public String doGet()
{
String uriAPI = "http://XXXXX?str=I+am+get+String";
String result= "";
// HttpGet httpRequst = new HttpGet(URI uri);
// HttpGet httpRequst = new HttpGet(String uri);
// 建立HttpGet或HttpPost物件,將要請求的URL通過構造方法傳入HttpGet或HttpPost物件。
HttpGet httpRequst = new HttpGet(uriAPI);
// new DefaultHttpClient().execute(HttpUriRequst requst);
try {
//使用DefaultHttpClient類的execute方法傳送HTTP GET請求,並返回HttpResponse物件。
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);//其中HttpGet是HttpUriRequst的子類
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出應答字串
// 一般來說都要刪除多餘的字元
result.replaceAll("\r", "");//去掉返回結果中的"\r"字元,否則會在結果字串後面顯示一個小方格
}
else
httpRequst.abort();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
HttpPost 如果使用HttpPost方法提交HTTP POST請求,則需要使用HttpPost類的setEntity方法設定請求引數。引數則必須用NameValuePair[]陣列儲存。
public String doPost()
{
String uriAPI = "http://XXXXXX";//Post方式沒有引數在這裡
String result = "";
HttpPost httpRequst = new HttpPost(uriAPI);//建立HttpPost物件
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
try {
httpRequst.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出應答字串
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
以傳送連線請求時,需要設定連結超時和請求超時等引數,否則會長期停止或者崩潰。
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//設定請求超時10秒
HttpConnectionParams.setSoTimeout(httpParameters, 10*1000); //設定等待資料超時10秒
HttpConnectionParams.setSocketBufferSize(params, 8192);
HttpClient httpclient = new DefaultHttpClient(httpParameters); //此時構造DefaultHttpClient時將引數傳入