码迷,mamicode.com
首页 > Web开发 > 详细

httpclient学习记录

时间:2015-12-29 14:12:51      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

---恢复内容开始---

此随笔都是一些网上的小实例,我学习后,添上一些注释。菜鸡程序员,水平较低,如有问题请指出。

httpclient是一种封装好的http协议的工具包,相对于httpconection来说,会比较简单,功能更多。

   HttpClient有两个重要方法,一个post,一个get,顾名思义一个是用来发送数据,得到返回值,一个是直接请求地址得到返回值。

  下面是几个post和get的实例:

  1.get小实例。

public class GGGGGG {
public String doGet(){
String url="http://www.123.com/xxxx/ccc";
String result ="";
HttpGet httpRequst = new HttpGet(url);
try{
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst); //执行获得返回值
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity = httpResponse.getEntity(); //得到报文
result = EntityUtils.toString(httpEntity); //转化格式
} else
httpRequst.abort(); //终止
}catch (ClientProtocolException e) {
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
}

这个例子是一个很简单的get实例,对取出来的数据只是做了一个转换类型的处理。注意httpRequst.abort() 这里 ,当发现返回的状态getStatusCode()不是200是,就是报错了,要关闭流。

2.get小实例。

public class HHH {
public static void main(String[] args) throws ClientProtocolException, IOException{
HttpClient hc = new DefaultHttpClient(); //新建接口子类
HttpGet hg = new HttpGet("http:www.baidu.com"); //封装请求地址
HttpResponse res = hc.execute(hg); //发送请求 得到返回值
HttpEntity entity = res.getEntity(); //取得报文 包含服务器响应内容
if(entity !=null){ //判断报文不为空
InputStream insm = entity.getContent(); //用流得到内容
String str = convertStreamToString(insm); //InputStream转化为String
hg.abort(); //http请求终止
}
}

public static String convertStreamToString(InputStream is){ //转换
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null ;
try{
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
} catch (IOException e){
e.printStackTrace();
}finally{
try{
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}

这个例子和上面例子一样,只是把流里的数据转换为了String类型。

 

3.post方法小实例

public class PPPP {

public String hPost(){
String url ="http://123.456.789.1";
String result = "";
HttpPost httpRequset = new HttpPost(url); //实例化http接口
List <NameValuePair> params = new ArrayList<NameValuePair>(); //实例化http数组
params.add(new BasicNameValuePair("content","I am so cool")); //放入参数
try{
httpRequset.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); //往报文中传入参数和字符编码
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequset); //执行或得返回值
if(httpResponse.getStatusLine().getStatusCode()== 200){
HttpEntity httpEntity = httpResponse.getEntity(); //得到返回报文
result = EntityUtils.toString(httpEntity); //转换为String格式
}
} catch (UnsupportedEncodingException e){
e.printStackTrace();
result = e.getMessage().toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
catch (IOException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
}

如果使用HttpPost方法提交HTTP POST请求,则需要使用HttpPost类的setEntity方法设置请求参数。参数则必须用NameValuePair[]数组存储

post方法 注意httpRequset.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)),UrlEncodedFormEntity方法百度到的意思是构造一个新的UrlEncodedFormEntity与列表指定的参数编码。我理解的是给params对应的字符编码设置为HTTP.UTF_8。平时使用post请求返回的字符尤其是汉字是乱码时,请检查这里的设置,改为与接口对应的字符编码。

4.post小实例

public class PPP {
public static void main(String[] args) { //post 我准备传的参数
String name ="joe";
String age ="22";
String content ="cool";
String ret = sendSms(name,age,content); //调用执行方法
System.out.println(ret);
if(ret.indexOf("失败")<0){
System.out.print("成功发送");
}
else{
System.out.print("发送失败");
}
}

public static String sendSms(String name,String age,String content){ //接收参数执行
HttpClient httpclient = new DefaultHttpClient(); //新建子类
String url = "http://192.168.0.1/aaaaa/sedsms";
HttpPost httppost = new HttpPost(url); //封装发送地址
String res = ""; //定义返回值

try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //实例化NameValuePair 传参
JSONObject jobj = new JSONObject(); //新建json对象放参数
jobj.put("name",name);
jobj.put("age",age);
jobj.put("content",content);

nameValuePairs.add(new BasicNameValuePair("msg", getStringFromJson(jobj))); //往NameValuePair传参
httppost.addHeader("Content-type", "application/x-www-form-urlencoded"); //设置http报文属性
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); //传入报文,设置文字编码
HttpResponse response = httpclient.execute(httppost); //执行获得返回值
if(response.getStatusLine().getStatusCode() == 200){ //返回200状态往下执行
String conResult = EntityUtils.toString(response.getEntity()); //得到返回报文 转换为string格式
JSONObject sobj = new JSONObject(); //新建json
sobj = sobj.fromObject(conResult); //得到的string对象内容转换为json对象
String result = sobj.getString("result"); //使用getString方法或得到值
String code = sobj.getString("code");
if(result.equals("1")){
res += "发送成功";
}else{
res += "发送失败,"+code;
}
} else {
String err = response.getStatusLine().getStatusCode()+"";
res += "发送失败:"+err; }
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return res;
}
private static String getStringFromJson(JSONObject adata) {       //拼参数
StringBuffer sb = new StringBuffer();
sb.append("{");
for(Object key:adata.keySet()){
sb.append("\""+key+"\":\""+adata.get(key)+"\",");
}
String rtn = sb.toString().substring(0, sb.toString().length()-1)+"}";
return rtn;
}
}


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 方法中的NameValuePair数组为HttpClient中特定的键值对数据存储类型,和form表单比较类似。

总结

使用 HttpClient 需要以下 6 个步骤:
1. 创建 HttpClient 的实例。
2. 创建某种连接方法的实例,httppost ,httpget ,GetMethod之类。
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的实例。
4. 读 response。
5. 释放连接。无论执行方法是否成功,都必须释放连接close(),abort()。
6. 对得到后的内容进行处理。
 
 
在发请求需要设置各项参数时可以参考如下:

HttpParams httpParameters = new BasicHttpParams();  

HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//设置请求超时10秒  

HttpConnectionParams.setSoTimeout(httpParameters, 10*1000); //设置等待数据超时10秒  

HttpConnectionParams.setSocketBufferSize(params, 8192);   //设置数据流长度

HttpClient httpclient = new DefaultHttpClient(httpParameters); //此时构造DefaultHttpClient时将参数传入  

 

getStatusCode()方法获取返回状态码,附上Http请求的状态码:

成功2××          成功处理了请求的状态码。

200 服务器已成功处理了请求并提供了请求的网页。

204 服务器成功处理了请求,但没有返回任何内容。
重定向3××       每次请求中使用重定向不要超过 5 次。
301 请求的网页已永久移动到新位置。当URLs发生变化时,使用301代码。搜索引擎索引中保存新的URL。
302 请求的网页临时移动到新位置。搜索引擎索引中保存原来的URL。
304 如果网页自请求者上次请求后没有更新,则用304代码告诉搜索引擎机器人,可节省带宽和开销。
客户端错误4×× 表示请求可能出错,妨碍了服务器的处理。
400 服务器不理解请求的语法。
403 服务器拒绝请求。
404 服务器找不到请求的网页。服务器上不存在的网页经常会返回此代码。
410 请求的资源永久删除后,服务器返回此响应。该代码与 404(未找到)代码相似,但在资源以前存在而现在不存在的情况下,有时用来替代404 代码。如果资源已永久删除,应当使用 301 指定资源的新位置。
服务器错误5×× 表示服务器在处理请求时发生内部错误。这些错误可能是服务器本身的错误,而不是请求出错。
500 服务器遇到错误,无法完成请求。
503 服务器目前无法使用(由于超载或停机维护)。通常,这只是暂时状态。

 

httpclient学习记录

标签:

原文地址:http://www.cnblogs.com/cloudjoe/p/5085327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!