HttpClient入门实例
来源:互联网 发布:长高知乎 编辑:程序博客网 时间:2024/06/01 10:11
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
- HttpClient入门实例
- httpClient实例
- httpclient 实例
- HttpClient实例
- HttpClient入门
- HttpClient入门
- httpClient入门
- HTTPClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- HttpClient入门
- mysqldump怎样导出一个库的多个表
- 接收json格式错误,开头出现多余问号
- 应用程序、内核和硬件的关系
- 如何在Windows中运行bash
- GitHub 前端工作面试问题
- HttpClient入门实例
- mysql常用命令集锦
- JAVA开发 电信支付系统短信模块精准发送短信
- iOS 统一编码风格的四种有效办法
- eclipse安装了tomcat7.0,启动后在window-> preferences选项中没有tomcat项
- svn删除文件引起的“...”missing from working copy
- ANDROID : java.lang.NoSuchMethodError: 在 org.apache.commons.codec.binary.Base64
- 定位“kubernetes pod卡在ContainerCreating状态”问题的方法
- 腾讯实习基础研究面试(包含一个编程题)