HttpClient4入门应用之二----Post方法访问Action带传参

Struts2的Action配置代码

 

 

<package name="Ajax" extends="json-default" namespace="/Ajax">
    <action name="serivceJ" class="com.wanghe.test.TestAction" method="serivceJ" >
   		<result  type="json"></result>
	</action>
</package>

 

Action代码

 

 

public void serivceJ() {
        try {
    HttpServletResponse response = ServletActionContext.getResponse(); 
HttpServletRequest request = ServletActionContext.getRequest();
 System.out.println("request...serivceJ");
	    response.setCharacterEncoding("UTF-8");
	        String type = request.getParameter("type");
	        String c = "none";
	        if(type.equalsIgnoreCase("girl")){
	        	c = "女孩你好!";
	        }else if(type.equalsIgnoreCase("boy")){
	        	c = "男孩你好!";
	        }
			response.getWriter().write(c);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 

HttpClient测试代码

 

//创建默认的httpClient实例.
HttpClient httpclient = new DefaultHttpClient();
//创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
//创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("type", "girl"));
UrlEncodedFormEntity uefEntity;
try {
	uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
	httppost.setEntity(uefEntity);
	System.out.println("executing request " + httppost.getURI());
	HttpResponse response;
	response = httpclient.execute(httppost);
	HttpEntity entity = response.getEntity();
	if (entity != null) {		System.out.println("--------------------------------------");
	System.out.println("Response content: " + EntityUtils.toString(entity,"UTF-8"));
System.out.println("--------------------------------------");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		}catch(UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
             //关闭连接,释放资源
			httpclient.getConnectionManager().shutdown();
		}

 

输出:

 

executing request http://localhost:8080/myDemo/Ajax/serivceJ.action
--------------------------------------
Response content: 女孩你好!
--------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值