httpClient jar包封装和使用

         HttpClient:可以用来在代码中模拟发送http请求的客户端工具包。

         发送http请求,接受http请求返回来的消息。

本文中给出的例子都是根据httpClient4.3.4.jar包编写的。

 

1.HttpGet

     

public String httpGet(String url){
		 String result=null;
         try {
    		 HttpGet httpGet = new HttpGet(url);
			 CloseableHttpResponse response = this.httpClient.execute(httpGet);
		     final int statusCode = response.getStatusLine().getStatusCode();
			 if(statusCode == org.apache.http.HttpStatus.SC_OK){  
		        	if (response.containsHeader("ERROR_SIGN")
							&& "Y".equals(response
									.getHeaders("ERROR_SIGN")[0]
									.getValue())) {
		            }
		        	else{
		        		HttpEntity entity = response.getEntity();
					result = EntityUtils.toString(entity);//获取字符串
					if(entity != null){
						final InputStream instream = entity.getContent();//访问url
						try{
							instream.read();
						}finally{
							instream.close();
						}
					}
					
					byte[] byteArray=EntityUtils.toByteArray(entity);//获取字节数字
				
                                           
		        	}
		     }else{

		     }
          
         } catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

   2.HttpPost,HttpPut,HttpDelete这些方法使用和上面例子差不多,只要将相应HttpGet换成HttpPost,HttpPut和HttpDelete实例即可。

  注意这些方法都要finally 释放连接

  以上这些例子,只是简单的介绍,实际上httpClient并没有这么简单,还有许多其他的知识点需要了解,比如说Http请求自动获取cookie,请求响应多长时间算失效,连接间隔等等。

 

    要想在已有工具基础上写出好的封装工具,需要会读文档,了解对象的基本含义和设置,拥有远见的思想。

   

   3.虽然觉得HttpPost等方法调用相似,但还是决定给个例子,写些返回方法的不同值的进行处理,包括设置HttpHeader等。

     HttpPost

     

protected void addMapToParamList(final List<NameValuePair> paramList,final Map<String,? extends Object> paramMap){
		if (paramMap != null) {
			for (final String key : paramMap.keySet()) {
				final Object value = paramMap.get(key);
				if(value instanceof List<?>){
					for(final String v : (List<String>)value){
						paramList.add(new BasicNameValuePair(key, v));
					}
				} else if(value.getClass().isArray()){
					for(final String v : (String[])value){
						paramList.add(new BasicNameValuePair(key, v));
					}
				}else{
					paramList.add(new BasicNameValuePair(key, (String)value));
				}
			}
		}
	}

   

public String httpPost(String url, Map<String, Object> paramsMap) {
		String result = null;
		final List<NameValuePair> paramList = new ArrayList<NameValuePair>();

		addMapToParamList(paramList, paramsMap);

		HttpEntity httpEntity;
		try {
			httpEntity = new UrlEncodedFormEntity(paramList,encode);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		final HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(httpEntity);
		try {

			CloseableHttpResponse response = this.httpClient.execute(httpPost);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == org.apache.http.HttpStatus.SC_OK) {
				if (response.containsHeader("ERROR_SIGN")
						&& "Y".equals(response.getHeaders("ERROR_SIGN")[0]
								.getValue())) {
				} else {
					HttpEntity entity1 = response.getEntity();
					result = EntityUtils.toString(entity1);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		return result;
	}

    4.HttpGet,HttpDelete,HttpPut,HttpPost这些都是HttpRequest对象的实现类,所以可以给他们设置request的内容,Header对象等(Accept-Type,Media-Type,Accept-Language等待),如果想要将返回的对象返回为json,xml等则加入一些jar包对象和json或xml的相互转换

    

  

   

你可能感兴趣的:(httpclient)