- 論壇徽章:
- 0
|
最近在做一個(gè)項(xiàng)目,里面有一個(gè)需求是需要通過java程序訪問一個(gè)http的接口,并且需要解析及獲取接口返回值,最后在網(wǎng)上查了資料,實(shí)現(xiàn)了此功能,將代碼和大家分享下。
通過java訪問http地址的實(shí)現(xiàn)方式有兩種,一種是post的方式,另外一種是get方式,下面就對(duì)兩種方式分別做一個(gè)介紹
[Java]代碼- 1、java代碼實(shí)現(xiàn)自動(dòng)訪問網(wǎng)站的代碼
- try {
- /** post方式 */
- HttpClient client = new HttpClient();
- PostMethod postMethod = new PostMethod(
- "http://localhost:8080/portal/check.jsp");
- // 參數(shù)設(shè)置
- postMethod.setParameter("channelid", "85");
- // 執(zhí)行postMethod
- client.getParams().setParameter(
- HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
- // 執(zhí)行并返回狀態(tài)
- int status = client.executeMethod(postMethod);
- String getUrl = postMethod.getResponseBodyAsString();
- System.out.println(getUrl);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- 2、check.jsp類的代碼
- <%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
- <%
- //通過欄目id判斷用戶對(duì)欄目權(quán)限;
- String channelid = (String) request.getParameter("channelid");
- if(null==channelid||""==channelid){
- response.getWriter().print(100);
- }else{
- response.getWriter().print(200);
- }
- %>
- 3、其輸出的結(jié)果為200.
- get方式實(shí)現(xiàn)
- // 構(gòu)造HttpClient的實(shí)例
- HttpClient httpClient = new HttpClient();
- // 創(chuàng)建GET方法的實(shí)例
- GetMethod getMethod = new GetMethod(url);
- // 使用系統(tǒng)提供的默認(rèn)的恢復(fù)策略
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
- new DefaultHttpMethodRetryHandler());
- // 定義一個(gè)輸入流
- InputStream ins = null;
- // 定義文件流
- BufferedReader br = null;
- try {
- // 執(zhí)行g(shù)etMethod
- int statusCode = httpClient.executeMethod(getMethod);
- if (statusCode != HttpStatus.SC_OK) {
- System.err.println("方法失敗: " + getMethod.getStatusLine());
- }
- // 使用getResponseBodyAsStream讀取頁(yè)面內(nèi)容,
- //這個(gè)方法對(duì)于目標(biāo)地址中有大量數(shù)據(jù)需要傳輸是最佳的。
- ins = getMethod.getResponseBodyAsStream();
- String charset = getMethod.getResponseCharSet();
- if (charset.toUpperCase().equals("ISO-8859-1")) {
- charset = "gbk";
- }
- // 按服務(wù)器編碼字符集構(gòu)建文件流,這里的CHARSET要根據(jù)實(shí)際情況設(shè)置
- br = new BufferedReader(new InputStreamReader(ins, getMethod
- .getResponseCharSet()));
- StringBuffer sbf = new StringBuffer();
- String line = null;
- while ((line = br.readLine()) != null) {
- sbf.append(line);
- }
- String result = new String(sbf.toString().getBytes(
- getMethod.getResponseCharSet()), charset);
- // 輸出內(nèi)容
- System.out.println(result);
-
- // 服務(wù)器編碼
- System.out.println("服務(wù)器編碼是:" + getMethod.getResponseCharSet());
- return result;
- } catch (HttpException e) {
- // 發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題
- System.out.println("請(qǐng)檢查您所提供的HTTP地址!");
- e.printStackTrace();
- } catch (IOException e) {
- // 發(fā)生網(wǎng)絡(luò)異常
- e.printStackTrace();
- } finally {
- // 關(guān)閉流,釋放連接
- }
- return null;
復(fù)制代碼 |
|