您的位置:首页 > 理论基础 > 计算机网络

HttpClient入门实例

2016-04-12 09:03 681 查看
Struts2的Action配置代码

Java代码


<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代码

Java代码


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测试代码

Java代码


//创建默认的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();
}

输出:

Java代码


executing request http://localhost:8080/myDemo/Ajax/serivceJ.action --------------------------------------
Response content: 女孩你好!
--------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: