HttpClient入门实例

来源:互联网 发布:长高知乎 编辑:程序博客网 时间:2024/06/01 10:11

Struts2的Action配置代码

 

 

Java代码  收藏代码
  1. <package name="Ajax" extends="json-default" namespace="/Ajax">  
  2.     <action name="serivceJ" class="com.wanghe.test.TestAction" method="serivceJ" >  
  3.         <result  type="json"></result>  
  4.     </action>  
  5. </package>  

 

Action代码

 

 

Java代码  收藏代码
  1. public void serivceJ() {  
  2.         try {  
  3.     HttpServletResponse response = ServletActionContext.getResponse();   
  4. HttpServletRequest request = ServletActionContext.getRequest();  
  5.  System.out.println("request...serivceJ");  
  6.         response.setCharacterEncoding("UTF-8");  
  7.             String type = request.getParameter("type");  
  8.             String c = "none";  
  9.             if(type.equalsIgnoreCase("girl")){  
  10.                 c = "女孩你好!";  
  11.             }else if(type.equalsIgnoreCase("boy")){  
  12.                 c = "男孩你好!";  
  13.             }  
  14.             response.getWriter().write(c);  
  15.         } catch (IOException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  

 

HttpClient测试代码

 

Java代码  收藏代码
  1. //创建默认的httpClient实例.  
  2. HttpClient httpclient = new DefaultHttpClient();  
  3. //创建httppost  
  4. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");  
  5. //创建参数队列  
  6. List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  7. formparams.add(new BasicNameValuePair("type""girl"));  
  8. UrlEncodedFormEntity uefEntity;  
  9. try {  
  10.     uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
  11.     httppost.setEntity(uefEntity);  
  12.     System.out.println("executing request " + httppost.getURI());  
  13.     HttpResponse response;  
  14.     response = httpclient.execute(httppost);  
  15.     HttpEntity entity = response.getEntity();  
  16.     if (entity != null) {       System.out.println("--------------------------------------");  
  17.     System.out.println("Response content: " + EntityUtils.toString(entity,"UTF-8"));  
  18. System.out.println("--------------------------------------");  
  19.             }  
  20.         } catch (ClientProtocolException e) {  
  21.             e.printStackTrace();  
  22.         }catch(UnsupportedEncodingException e1) {  
  23.             e1.printStackTrace();  
  24.         }catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }finally{  
  27.              //关闭连接,释放资源  
  28.             httpclient.getConnectionManager().shutdown();  
  29.         }  

 

输出:

 

Java代码  收藏代码
  1. executing request http://localhost:8080/myDemo/Ajax/serivceJ.action  
  2. --------------------------------------  
  3. Response content: 女孩你好!  
  4. -------------------------------------- 
0 0