qjfhy

博客园 首页 新随笔 联系 订阅 管理

CommonUtils类

package com.paic.mamc.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class CommonUtils {

 private static HttpClient hc = new DefaultHttpClient();
 
 /**
  * post 方法
  *
  * @param url
  * @param params
  * @return
  */
 @Test
 public static String post(String url, List<NameValuePair> params) {
  String body = null;
  try {
   HttpPost httppost = new HttpPost(url);
   httppost.setEntity(new UrlEncodedFormEntity(params));
   
   HttpResponse httpresponse = hc.execute(httppost);
   HttpEntity entity = httpresponse.getEntity();
   body = EntityUtils.toString(entity);
   
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch(Exception e){
   e.printStackTrace();
  }

  return body;

 }
 
 /**
  * get方法
  * @param url
  * @return
  */
 public static String get(String url) {
  // String uri =
  // "http://localhost:8080/CAS/rest/testRest?pafaJsonpCallbak=callback";
  try {
  HttpGet get = new HttpGet(url);
  HttpResponse response;
   response = hc.execute(get);
   HttpEntity entity = response.getEntity();
   System.out.println(entity == null ? null : EntityUtils
     .toString(entity));

   return EntityUtils.toString(entity);
  } catch (ClientProtocolException e) {
   System.out.println("不应该到达这里");
   e.printStackTrace();
   
  } catch (IOException e) {
   System.out.println("不应该到达这里");
   e.printStackTrace();
  } catch(Exception e){
   e.printStackTrace();
  }

  return "";
 }
}

 

测试类

@Test
 public void test() {
   
   String url= "http://localhost:7001/MAMC/mamc/vcode.do";
   
   List<NameValuePair> params = new ArrayList<NameValuePair>();
   
   //String timestamp = String.valueOf(System.currentTimeMillis());
   params.add(new BasicNameValuePair("appId", "10043"));
   
   String body = CommonUtils.post(url, params);
   
   System.out.println("==="+body);
  
 }

posted on 2014-03-24 10:43  qjfhy  阅读(223)  评论(1)    收藏  举报