`
wxlgzxx_1988
  • 浏览: 66174 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

HttpClient基本功能使用(结合Struts2传参)

阅读更多

HttpClient基本功能的使用

a)    环境准备

·         apache下载httpClient;

·         解压、将lib下的jar导入工程;

b)   几个主要类解释

类名

作用

HttpClient

HttpClient代表了一个http的客户端,HttpClient接口定义了大多数基本的http请求执行行为.

HttpEntity

entity是发送或者接收消息的载体。entities 可以通过requestresponse获取到.

HttpConnection

HttpConnection代表了一个http连接。

 

 

 

 

 

 

 

c)    第一个程序

说明: get方法访问www.baidu.com并返回内容

Code:

 

Testing Code

//创建默认的httpClient实例.

HttpClient httpclient = new DefaultHttpClient();

try {

//创建httpget.

   HttpGet httpget = new HttpGet("http://www.baidu.com/");

System.out.println("executing request " + httpget.getURI());

//执行get请求.

   HttpResponse response = httpclient.execute(httpget);

//获取响应实体

   HttpEntity entity = response.getEntity();

System.out.println("--------------------------------------");

//打印响应状态

   System.out.println(response.getStatusLine());

      if (entity != null) {

//打印响应内容长度

          System.out.println("Response content length: " + entity.getContentLength());

//打印响应内容

         System.out.println("Response content: " + EntityUtils.toString(entity));

            }

        System.out.println("------------------------------------");

        } finally {

            //关闭连接,释放资源

            httpclient.getConnectionManager().shutdown();

        }

 

输出:

executing request http://www.baidu.com/

----------------------------------------

HTTP/1.1 200 OK

Response content length: 6759

Response content: <!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>百度一下,你就知道      </title>…(此处省略打印信息)

-----------------------------------------

a)    如何传递参数

说明: post方法访问本地应用并根据传递参数不同返回不同结果

Code:

 

Struts2配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
        "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.i18n.encoding" value="UTF-8"></constant>

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

	<!-- 
		<package name="test" extends="struts-default" namespace="/test">
		<action name="test" class="com.wxl.action.TestAction"
		method="serivceJ">
		<result>/index.jsp</result>
		</action>
		</package>
	-->

</struts>

  

Action Code

/**
 * 
 */
package com.wxl.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author wangxl
 * 
 */
public class TestAction extends ActionSupport {

	public void serivceJ() throws Exception {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			HttpServletRequest request = ServletActionContext.getRequest();
			response.setCharacterEncoding("UTF-8");
			String type = request.getParameter("type");
			String c = "none";
			if (type != null && !"".equals(type)) {
				if (type.equalsIgnoreCase("car")) {
					c = "Hello:给你一辆宝马";
				} else if (type.equalsIgnoreCase("house")) {
					c = "Hello:给你一栋别墅";
				}
			}
			response.getWriter().write(c);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

 

TestingCode

/**
 * 
 */
package com.wxl.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author wangxl
 * 
 */
public class HttpClientTest {

	private static String url = "http://localhost:8088/Struts2/Ajax/serivceJ.action";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 创建默认的httpClient实例
		HttpClient httpclient = new DefaultHttpClient();
		// 创建post请求
		HttpPost post = new HttpPost(url);
		// 创建参数队列
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("type", "car"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(uefEntity);
			System.out.println("--------------------------------------");
			System.out.println("Executing request url:" + post.getURI());
			HttpResponse response = httpclient.execute(post);
			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 url:http://localhost:8088/Struts2/Ajax/serivceJ.action
--------------------------------------
Response content: Hello:给你一辆宝马
--------------------------------------

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics