java實現自動訪問網站並獲取返回值的代碼

post方式實現html

一、java代碼實現自動訪問網站的代碼java

try {
    /** post方式 */
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod("http://localhost:8080/portal/check.jsp");
    // 參數設置
    postMethod.setParameter("channelid", "85");
    // 執行postMethod
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    // 執行並返回狀態
    int status = client.executeMethod(postMethod);
    String getUrl = postMethod.getResponseBodyAsString();
    System.out.println(getUrl);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

二、check.jsp類的代碼服務器

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<%
//經過欄目id判斷用戶對欄目權限;
String channelid = (String) request.getParameter("channelid");
if(null==channelid||""==channelid){
    response.getWriter().print(100);
}else{
    response.getWriter().print(200);
}
%>

三、其輸出的結果爲200.網絡

get方式實現app

// 構造HttpClient的實例
HttpClient httpClient = new HttpClient();
// 建立GET方法的實例
GetMethod getMethod = new GetMethod(url);
// 使用系統提供的默認的恢復策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        new DefaultHttpMethodRetryHandler());
// 定義一個輸入流
InputStream ins = null;
// 定義文件流
BufferedReader br = null;
try {
    // 執行getMethod
    int statusCode = httpClient.executeMethod(getMethod);
    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("方法失敗: " + getMethod.getStatusLine());
    }
    // 使用getResponseBodyAsStream讀取頁面內容,
    //這個方法對於目標地址中有大量數據須要傳輸是最佳的。
    ins = getMethod.getResponseBodyAsStream();
    String charset = getMethod.getResponseCharSet();
    if (charset.toUpperCase().equals("ISO-8859-1")) {
        charset = "gbk";
    }
    // 按服務器編碼字符集構建文件流,這裏的CHARSET要根據實際狀況設置
    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);
    // 輸出內容
    System.out.println(result);
 
    // 服務器編碼
    System.out.println("服務器編碼是:" + getMethod.getResponseCharSet());
    return result;
} catch (HttpException e) {
    // 發生致命的異常,多是協議不對或者返回的內容有問題
    System.out.println("請檢查您所提供的HTTP地址!");
    e.printStackTrace();
} catch (IOException e) {
    // 發生網絡異常
    e.printStackTrace();
} finally {
    // 關閉流,釋放鏈接
}
return null;
相關文章
相關標籤/搜索