httpclient

来源:互联网 发布:入侵五角大楼的网络 编辑:程序博客网 时间:2024/05/01 09:21

package test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**

*/

public class Authentication {
 
 private static final String CONTENT_CHARSET = "GB2312";// httpclient读取内容时使用的字符集

 

 /**
  *
  * 的到Http请求结果
  *
  * @param url请求地址
  *
  * @param parms请求参数
  *
  * @return
  *
  */

 public String getBody(String url, Map parms) {

  String body = null;

  // 构造HttpClient的实例

  HttpClient httpClient = new HttpClient();

  // 创建GET方法的实例

  PostMethod postMethod = new PostMethod(url);
  
  //httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
  //httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, "US-ASCII");

  //postMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
 // postMethod.getParams().setContentCharset("GB2312"); 
  // 填入各个表单域的值
  
  NameValuePair[] data = new NameValuePair[parms.keySet().size()];
  Iterator it = parms.entrySet().iterator();

  int i = 0;

  while (it.hasNext()) {
   Map.Entry entry = (Map.Entry) it.next();
   Object key = entry.getKey();
   Object value = entry.getValue();
   data[i] = new NameValuePair(key.toString(), value.toString());

   i++;

  }

  //httpClient.getParams().setParameter(
     //  HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);

  // 将表单的值放入postMethod中

  postMethod.setRequestBody(data);

  try {

   // 执行postMethod

   int statusCode = httpClient.executeMethod(postMethod); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发

   // 301或者302

//   if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
//     || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
//
//    // 从头中取出转向的地址
//
//    Header locationHeader = postMethod
//      .getResponseHeader("location");
//
//    String location = null;
//
//    if (locationHeader != null) {
//     location = locationHeader.getValue();
//    // System.out
//    //   .println("The page was redirected to:" + location);
//
//    } else {
//
//    // System.err.println("Location field value is null.");
//
//    }
//
//   }
    //检查是否重定向

  //       int statuscode = post.getStatusCode();
    GetMethod redirect = null;
         if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) ||

             (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) ||

             (statusCode == HttpStatus.SC_SEE_OTHER) ||

 (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

 //读取新的URL地址
          //System.out.println("Invalid redirect");
             Header header = postMethod.getResponseHeader("location");

             if (header != null) {

                 String newuri = header.getValue();

                 if ((newuri == null) || (newuri.equals("")))

                     newuri = "/";
                // System.out.println("Invalid redirect");
               
                  redirect = new GetMethod(newuri);
                 httpClient.executeMethod(redirect);

                // System.out.println("Redirect:"+ redirect.getResponseBodyAsString());
                // System.out.println("Invalid redirect");
               //  redirect.releaseConnection();

             } else

                 System.out.println("Invalid redirect");

         }

 

   body = postMethod.getResponseBodyAsString();
   if(null==body){
    body=redirect.getResponseBodyAsString();
   }

  } catch (Exception e) {

   e.printStackTrace();

  }

  return body;

 }
 
 public String getURL(String url, Map parms) {

  String body = null;

  // 构造HttpClient的实例

  HttpClient httpClient = new HttpClient();

  // 创建GET方法的实例

  PostMethod postMethod = new PostMethod(url);
  
  //httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
  //httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, "US-ASCII");

  //postMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
 // postMethod.getParams().setContentCharset("GB2312"); 
  // 填入各个表单域的值
  
  NameValuePair[] data = new NameValuePair[parms.keySet().size()];
  Iterator it = parms.entrySet().iterator();

  int i = 0;

  while (it.hasNext()) {
   Map.Entry entry = (Map.Entry) it.next();
   Object key = entry.getKey();
   Object value = entry.getValue();
   data[i] = new NameValuePair(key.toString(), value.toString());

   i++;

  }

  //httpClient.getParams().setParameter(
     //  HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);

  // 将表单的值放入postMethod中

  postMethod.setRequestBody(data);

  try {

   // 执行postMethod

   int statusCode = httpClient.executeMethod(postMethod); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发

   // 301或者302

   if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
     || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {

    // 从头中取出转向的地址

    Header locationHeader = postMethod
      .getResponseHeader("location");

    String location = null;

    if (locationHeader != null) {
     location = locationHeader.getValue();
     body=location;
    // System.out
    //   .println("The page was redirected to:" + location);

    } else {

    // System.err.println("Location field value is null.");

    }

   }

  // body = postMethod.getResponseBody();
  // body = postMethod.getResponseBody();
  } catch (Exception e) {

   e.printStackTrace();

  }

  return body;

 }

 public static void main(String[] args) {

 // String url = "http://localhost:8080/httpclienttest/test.xml";
  String url = "http://localhost:8080/httpclienttest/";

  Map parms = new HashMap();
  parms.put("user", "yanbo");
  parms.put("pass", "1234");
  
  
  //parms.put("j_username", "admin");
  //parms.put("j_password", "admin123");

  Authentication client = new Authentication();

  String result = new String(client.getBody(url, parms));
  System.out.println(result);

 }
}

原创粉丝点击