httpclient Post请求_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > httpclient Post请求

httpclient Post请求

 2014/12/18 15:32:19  lqi  程序员俱乐部  我要评论(0)
  • 摘要:1、使用httpclient请求服务2、需要的java包privatestaticLoggerlog=Logger.getLogger(ServiceLink.class);privatestaticHttpClientclient=newHttpClient();privatestaticbooleanflog=true;/***post请求方法传递地址
  • 标签:client HTTP

1、使用httpclient请求服务?

2、需要的java包

class="java" name="code">	private static Logger log = Logger.getLogger(ServiceLink.class);
	private static HttpClient client = new HttpClient();
	private static boolean flog=true;
	
	
	
	
	/**
	 * post请求方法  传递地址 、数据
	 * @param url
	 * @param datas
	 * @return
	 */
	public static String getPostMethodWrite(String url,String datas){
		
		 if(flog){
			 
			 flog=false;
			 PostMethod postMethod = new PostMethod(url);
			 //设置参数编码为utf-8
			 postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
			 //构造键值对参数
			 NameValuePair[] data = { new NameValuePair("data", datas)}; 
			 // 把参数值放入postMethod中 
			 postMethod.setRequestBody(data);
			 //执行
			 try {
				client.executeMethod(postMethod);
				 //读取内容
			     byte[] responseBody = postMethod.getResponseBody();
			     //处理内容
//			     System.out.println(new String(responseBody));
//			         System.out.println("statusCode:"+statusCode);
			         //打印结果页面
			         String response =  new String(postMethod.getResponseBodyAsString().getBytes("utf-8"));
			        //打印返回的信息
			         log.info("response:"+response);
			         return response;
			 //释放连接
			
			} catch (HttpException e) {

				ErrorPrint.sprintLog(e, log,"http协议异常");
				e.printStackTrace();
				return "";
				
			} catch (IOException e) {
				ErrorPrint.sprintLog(e, log,"流异常");
				log.error("流异常", e);
				e.printStackTrace();
				return "";
			} finally{
				 postMethod.releaseConnection();
				 flog=true;
			}
		 }
		 return "";
	}

?

发表评论
用户名: 匿名