http协议

来源:互联网 发布:java cache框架 编辑:程序博客网 时间:2024/06/06 03:21
1 http协议表示通过http协议(网址http://xxxxx)的方式来调用远程地址,并返回结果。通常需要加载http协议满足的jar:commons-logging-1.1.1.jar、httpcomponents.jar、httpcore.jar


2 http协议如果想要传输并返回结果,需要有url和parameter,url表示网址,parameter表示参数。需要有DefaultHttpClient、HttpPost、StringEntity。DefaultHttpClient用来执行execute方法。HttpPost用来设置url和设置StringEntity属性。StringEntity用来设置parameter
如:DefaultHttpClient client=new DefaultHttpClient();//创建一个client
HttpPost post=new HttpPost(url);//这里传递url
StringEntity entity=new StringEntity(parameter);//这里传递parameter
post.setEntity(entity);//将entity赋值给httppost


3 通过DefaultHttpClient执行execute方法就可以得到返回结果。得到的是HttpResponse。
如:HttpResponse response=client.execute(post);


4 得到HttpResponse就可以得到结果内容。通过HttpResponse.getEntity()得到Entity。然后通过EntityUtils.toString(Entity entity)方法得到字符格式的结果内容。
如:HttpResponse response=client.execute(post);
neirong=EntityUtils.toString(response.getEntity());//这样就得到了结果。
System.out.println(neirong);




完整的例子:


HttpUtils httpUtils=new HttpUtils();
String url="http://www.meetav.com";
String parameter="a=123";
httpUtils.httpReqMethod(url, parameter);


httpReqMethod方法如下:


public String httpReqMethod(String url,String parameter){
String neirong=null;
try {
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
StringEntity entity=new StringEntity(parameter);
post.setEntity(entity);

HttpResponse response=client.execute(post);
//InputStream inputStream=response.getEntity().getContent();
neirong=EntityUtils.toString(response.getEntity());
System.out.println(neirong);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return neirong;
}

原创粉丝点击