HttpClient HttpServlet HttpUrlConnection

HttpServerlet 属于服务器端的内容:

Servlet的框架是由两个Java包组成:javax.servlet和javax.servlet.http。 在javax.servlet包中定义了所有的Servlet类都必须实现或扩展的的通用接口和类,在javax.servlet.http包中定义了采用HTTP通信协议的HttpServlet类。
Servlet的框架的核心是javax.servlet.Servlet接口,所有的Servlet都必须实现这一接口。在Servlet接口中定义了5个方法,其中有3个方法代表了Servlet的生命周期:
init方法,负责初始化Servlet对象
service方法,负责响应客户的请求
destroy方法,当Servlet对象退出生命周期时,负责释放占有的资源
Servlet被设计成请求驱动的.Servlet的请求可能包含多个数据项,当Web容器接收到某个Servlet请求时,Web容器把请求封装成一个HttpServletRequest对象,然后把对象传给Servlet的对应的服务方法.
HTTP的请求方式包括DELETE,GET,OPTIONS,POST,PUT和TRACE,在HttpServlet类中分别提供了相应的服务方法,它们是,doDelete(),doGet(),doOptions(),doPost(), doPut()和doTrace().
HttpServlet容器响应Web客户请求流程如下:
1)Web客户向Servlet容器发出Http请求;
2)Servlet容器解析Web客户的Http请求;
3)Servlet容器创建一个HttpRequest对象,在这个对象中封装Http请求信息;
4)Servlet容器创建一个HttpResponse对象;
5)Servlet容器调用HttpServlet的service方法,把HttpRequest和HttpResponse对象作为service方法的参数传给HttpServlet对象;
6)HttpServlet调用HttpRequest的有关方法,获取HTTP请求信息;
7)HttpServlet调用HttpResponse的有关方法,生成响应数据;
8)Servlet容器把HttpServlet的响应结果传给Web客户。
 
 
 
HttpUrlConeection则是jdk提供的一个客户端发送请求的类

一、使用HttpURLConnection向服务器发送get请求

1、向服务器发送get请求

复制代码
    @Test
publicvoid sendSms() throws Exception{
String message="货已发到";
message=URLEncoder.encode(message, "UTF-8");
System.out.println(message);
String path ="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
URL url =new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
byte[] data = StreamTool.readInputStream(inStream);
String result=new String(data, "UTF-8");
System.out.println(result);
}
复制代码

2、从服务器读取数据    

String message=request.getParameter("message");

            

               

二、使用HttpURLConnection向服务器发送post请求

1、向服务器发送post请求

复制代码
    @Test
publicvoid addByUrl() throws Exception{
String encoding="UTF-8";
String params="[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
String path ="http://localhost:8083/xxxx/xxx/sim!add.do";
byte[] data = params.getBytes(encoding);
URL url =new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5*1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode()); //响应代码 200表示成功
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream();  
String result=new String(StreamTool.readInputStream(inStream), "UTF-8");
}
}
复制代码

                

2、从服务器读取数据   

//获取post请求过来的数据
byte[] data=StreamTool.readInputStream(request.getInputStream());
//[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]
String json=new String(data, "UTF-8");
 
 
 
HttpClient则是apache组织的封装的一个客户端的工具
HttpClient:是一个接口

//首先需要先创建一个DefaultHttpClient的实例

HttpClient httpClient=new DefaultHttpClient();

//发送GET请求:

//先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:

HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);

httpClient.execute(httpGet);

//发送POST请求:

//创建一个HttpPost对象,传入目标的网络地址:

HttpPost httpPost=new HttpPost(“http://www.baidu.com”);

//通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入:

List<NameValuePair>params=newArrayList<NameValuePair>();

Params.add(new BasicNameValuePair(“username”,”admin”));

Params.add(new BasicNameValuePair(“password”,”123456”));

UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);

httpPost.setEntity(entity);

//调用HttpClient的execute()方法,并将HttpPost对象传入即可:

HttpClient.execute(HttpPost);

//执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse里面.先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:

If(httpResponse.getStatusLine().getStatusCode()==200){

//请求和响应都成功了

HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例

Stringresponse=EntityUtils.toString(entity,”utf-8”);//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了

}

 

posted on 2016-03-24 14:41  1204771796  阅读(555)  评论(0编辑  收藏  举报

导航