程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 編程-關於HttpClient的問題,如何使用HttpClient重定向?

編程-關於HttpClient的問題,如何使用HttpClient重定向?

編輯:編程綜合問答
關於HttpClient的問題,如何使用HttpClient重定向?
 /*
 * HttpRequestProxy.java
 *
 * Created on November 3, 2008, 9:53 AM
 */


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;


public class HttpRequestProxy {
    // 超時間隔
    private static int connectTimeOut = 60000;
    // 讓connectionmanager管理httpclientconnection時是否關閉連接
    private static boolean alwaysClose = false;
    // 返回數據編碼格式
    private String encoding = "UTF-8";

    private final HttpClient client = new HttpClient();

    public HttpClient getHttpClient() {
        return client;
    }
    /**
     * 用法: HttpRequestProxy hrp = new HttpRequestProxy();
     * hrp.doRequest("http://www.163.com",null,null,"gbk");
     * 
     * @param url
     *            請求的資源URL
     * @param postData
     *            POST請求時form表單封裝的數據 沒有時傳null
     * @param header
     *            request請求時附帶的頭信息(header) 沒有時傳null
     * @param encoding
     *            response返回的信息編碼格式 沒有時傳null
     * @return response返回的文本數據
     * @throws CustomException
     */
    public String doRequest(String url, Map postData, Map header, String encoding) throws Exception {
        String responseString = null;
        // 頭部請求信息
        Header[] headers = null;
        if (header != null) {
            Set entrySet = header.entrySet();
            int dataLength = entrySet.size();
            headers = new Header[dataLength];
            int i = 0;
            for (Iterator itor = entrySet.iterator(); itor.hasNext();) {
                Map.Entry entry = (Map.Entry) itor.next();
                headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString());
            }
        }

        // post方式
        if (postData != null) {
            PostMethod postRequest = new PostMethod(url.trim());
            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    postRequest.setRequestHeader(headers[i]);
                }
            }
            Set entrySet = postData.entrySet();
            int dataLength = entrySet.size();
            NameValuePair[] params = new NameValuePair[dataLength];
            int i = 0;
            for (Iterator itor = entrySet.iterator(); itor.hasNext();) {
                Map.Entry entry = (Map.Entry) itor.next();
                params[i++] = new NameValuePair(entry.getKey().toString(), entry.getValue().toString());
            }
            postRequest.setRequestBody(params);
            try {
                responseString = this.executeMethod(postRequest, encoding);
            } catch (Exception e) {
                throw e;
            } finally {
                postRequest.releaseConnection();
            }
        }
        return responseString;
    }

    private String executeMethod(HttpMethod request, String encoding) throws Exception {
        String responseContent = null;
        InputStream responseStream = null;
        BufferedReader rd = null;
        try {
            this.getHttpClient().executeMethod(request);
            if (encoding != null) {
                responseStream = request.getResponseBodyAsStream();
                rd = new BufferedReader(new InputStreamReader(responseStream, encoding));
                String tempLine = rd.readLine();
                StringBuffer tempStr = new StringBuffer();
                String crlf = System.getProperty("line.separator");
                while (tempLine != null) {
                    tempStr.append(tempLine);
                    tempStr.append(crlf);
                    tempLine = rd.readLine();
                }
                responseContent = tempStr.toString();
            } else
                responseContent = request.getResponseBodyAsString();

            Header locationHeader = request.getResponseHeader("location");
            // 返回代碼為302,301時,表示頁面己經重定向,則重新請求location的url,這在
            // 一些登錄授權取cookie時很重要
            if (locationHeader != null) {
                String redirectUrl = locationHeader.getValue();
                this.doRequest(redirectUrl, null, null, null);
            }
        } catch (HttpException e) {
            throw new Exception(e.getMessage());
        } catch (IOException e) {
            throw new Exception(e.getMessage());

        } finally {
            if (rd != null)
                try {
                    rd.close();
                } catch (IOException e) {
                    throw new Exception(e.getMessage());
                }
            if (responseStream != null)
                try {
                    responseStream.close();
                } catch (IOException e) {
                    throw new Exception(e.getMessage());

                }
        }
        return responseContent;
    }

    /**
     * 特殊請求數據,這樣的請求往往會出現redirect本身而出現遞歸死循環重定向 所以單獨寫成一個請求方法
     * 比如現在請求的url為:http://localhost:8080/demo/index.jsp 返回代碼為302
     * 頭部信息中location值為:http://localhost:8083/demo/index.jsp
     * 這時httpclient認為進入遞歸死循環重定向,拋出CircularRedirectException異常
     * 
     * @param url
     * @return
     * @throws CustomException
     */
    public String doSpecialRequest(String url, int count, String encoding) throws Exception {
        String str = null;
        InputStream responseStream = null;
        BufferedReader rd = null;
        GetMethod getRequest = new GetMethod(url);
        // 關閉httpclient自動重定向動能
        getRequest.setFollowRedirects(false);
        try {

            this.client.executeMethod(getRequest);
            Header header = getRequest.getResponseHeader("location");
            if (header != null) {
                // 請求重定向後的URL,count同時加1
                this.doSpecialRequest(header.getValue(), count + 1, encoding);
            }
            // 這裡用count作為標志位,當count為0時才返回請求的URL文本,
            // 這樣就可以忽略所有的遞歸重定向時返回文本流操作,提高性能
            if (count == 0) {
                getRequest = new GetMethod(url);
                getRequest.setFollowRedirects(false);
                this.client.executeMethod(getRequest);
                responseStream = getRequest.getResponseBodyAsStream();
                rd = new BufferedReader(new InputStreamReader(responseStream, encoding));
                String tempLine = rd.readLine();
                StringBuffer tempStr = new StringBuffer();
                String crlf = System.getProperty("line.separator");
                while (tempLine != null) {
                    tempStr.append(tempLine);
                    tempStr.append(crlf);
                    tempLine = rd.readLine();
                }
                str = tempStr.toString();
            }

        } catch (HttpException e) {
            throw new Exception(e.getMessage());
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        } finally {
            getRequest.releaseConnection();
            if (rd != null)
                try {
                    rd.close();
                } catch (IOException e) {
                    throw new Exception(e.getMessage());
                }
            if (responseStream != null)
                try {
                    responseStream.close();
                } catch (IOException e) {
                    throw new Exception(e.getMessage());
                }
        }
        return str;
    }

    public static void main(String[] args) throws Exception {

        HttpRequestProxy hrp = new HttpRequestProxy();
        Map date = new HashMap();
        date.put("jyidApplet", "1");
        date.put("codeNumApplet", "1");
        date.put("jymxIdApplet", "447");
        date.put("patientIdApplet", "1118");
        String str = hrp.doRequest("http://127.0.0.1:8080/lis/mz/addTM",date, null, null);
        System.out.println(str);

    }

}

最佳回答:


HttpClient重定向
httpclient重定向
----------------------同志你好,我是CSDN問答機器人小N,奉組織之命為你提供參考答案,編程尚未成功,同志仍需努力!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved