java抓取有驗證的頁面內容

木坦坦發表於2016-01-26
package zz.test.ssm.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/mq")
public class MqQueueController {


    @RequestMapping(value = "queue", method = RequestMethod.GET)
    @ResponseBody
    public String getMqQueue(HttpServletRequest request) throws HttpException, IOException {
        String response = "";
        String queueName = request.getParameter("queue");
        String username = "user";
        String password = "pass";
        String url = "http://192.168.50.2:1002/api/queues/%2Femsfeedback/"+queueName;  


        HttpClient client = new HttpClient();
        client.getState().setCredentials(
                new AuthScope("192.168.50.2", 1002),
                new UsernamePasswordCredentials(username, password));
        GetMethod get = new GetMethod( url );
        get.setDoAuthentication( true );
        int status = client.executeMethod( get );
        response = get.getResponseBodyAsString();
        System.out.println(status+ "\n" + get.getResponseBodyAsString());
        get.releaseConnection();
        return response;
    }
}

參考:
http://www.blogjava.net/jelver/articles/162339.html
http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113247.html

相關文章