java中httpclient实现digest验证的请求

1、首先介绍如何使用HttpClient发起GET和POST请求

GET 方式:
//先将参数放入List,再对参数进行URL编码

List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();

params.add(new BasicNameValuePair("param1", "中国"));

params.add(new BasicNameValuePair("param2", "value2"));

 
//对参数编码

String param = URLEncodedUtils.format(params, "UTF-8");

 
//baseUrl           

String baseUrl = "

 
 
//将URL与参数拼接

HttpGet getMethod = new HttpGet(baseUrl + "?" + param);

             

HttpClient httpClient = new DefaultHttpClient();

 

try {

    HttpResponse response = httpClient.execute(getMet搜索hod); //发起GET请求

 

    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码

    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容

} catch (ClientProtocolException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

} catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

} 


 
POST方式:
//和GET方式一样,先将参数放入List

params = new LinkedList<BasicNameValuePair>();

params.add(new BasicNameValuePair("param1", "Post方法"));

params.add(new BasicNameValuePair("param2", "第二个参数"));

             

try {

    HttpPost postMethod = new HttpPost(baseUrl);

    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中

                 

    HttpResponse response = httpClient.execute(postMethod); //执行POST方法

    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码

    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容

                 

} catch (UnsupportedEncodingException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

} catch (ClientProtocolException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

} catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

} 

 2、httpclient的digest验证,需要tomcat服务器配置digest验证,具体配置参见先前博文。                    
                 
  1. package test.util;  
  2.   
  3. import java.net.URI;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.commons.httpclient.auth.AuthPolicy;  
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.auth.AuthScope;  
  10. import org.apache.http.auth.Credentials;  
  11. import org.apache.http.auth.UsernamePasswordCredentials;  
  12. import org.apache.http.client.methods.HttpUriRequest;  
  13. import org.apache.http.impl.auth.DigestSchemeFactory;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15.   
  16. /** 
  17.  * @author Administrator 
  18.  *  
  19.  */  
  20. public class HTTPDigestClient {  
  21.     private URI serverURI = null;  
  22.     String response = null;  
  23.     private DefaultHttpClient httpClient = new DefaultHttpClient();  
  24.   
  25.     /** 
  26.      * constructor 
  27.      */  
  28.     public HTTPDigestClient(String userName, String passWord, String url) {  
  29.         try {  
  30.             serverURI = new URI(url);  
  31.             Credentials creds = new UsernamePasswordCredentials(userName,  
  32.                     passWord);  
  33.   
  34.             httpClient.getCredentialsProvider().setCredentials(  
  35.                     new AuthScope(serverURI.getHost(), serverURI.getPort), (Credentials) creds);  
  36.   
  37.             httpClient.getParams().setParameter(  
  38.                     AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));  
  39.             httpClient.getAuthSchemes().register(AuthPolicy.DIGEST,  
  40.                     new DigestSchemeFactory());  
  41.   
  42.         } catch (Exception e) {  
  43.               
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      * send request to server 
  49.      *  
  50.      * @param httpClient 
  51.      * @param httpUriRequest 
  52.      * @return response HttpResponse 
  53.      */  
  54.     public HttpResponse send(HttpUriRequest httpUriRequest) {  
  55.         HttpResponse response = null;  
  56.         try {  
  57.             if (null == httpClient) {  
  58.                   
  59.                 return response;  
  60.             }  
  61.             response = httpClient.execute(httpUriRequest);  
  62.   
  63.         } catch (Exception e) {  
  64.               
  65.         }  
  66.         return response;  
  67.     }  
  68.   
  69. }  
package test.util;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author Administrator
 * 
 */
public class HTTPDigestClient {
	private URI serverURI = null;
	String response = null;
	private DefaultHttpClient httpClient = new DefaultHttpClient();

	/**
	 * constructor
	 */
	public HTTPDigestClient(String userName, String passWord, String url) {
		try {
			serverURI = new URI(url);
			Credentials creds = new UsernamePasswordCredentials(userName,
					passWord);

			httpClient.getCredentialsProvider().setCredentials(
					new AuthScope(serverURI.getHost(), serverURI.getPort), (Credentials) creds);

			httpClient.getParams().setParameter(
					AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));
			httpClient.getAuthSchemes().register(AuthPolicy.DIGEST,
					new DigestSchemeFactory());

		} catch (Exception e) {
			
		}
	}

	/**
	 * send request to server
	 * 
	 * @param httpClient
	 * @param httpUriRequest
	 * @return response HttpResponse
	 */
	public HttpResponse send(HttpUriRequest httpUriRequest) {
		HttpResponse response = null;
		try {
			if (null == httpClient) {
				
				return response;
			}
			response = httpClient.execute(httpUriRequest);

		} catch (Exception e) {
			
		}
		return response;
	}

}

 

服务器端必须加入域

设置realm 为空或者当前域名 测试成功

用户名 密码用的是域账户

下面为basic验证方式 ,测试通过

 

  1. package test.util;  
  2.   
  3. import java.net.URI;  
  4. import java.util.Collections;  
  5.   
  6. import org.apache.commons.httpclient.auth.AuthPolicy;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.auth.AuthScope;  
  9. import org.apache.http.auth.Credentials;  
  10. import org.apache.http.auth.UsernamePasswordCredentials;  
  11. import org.apache.http.client.CredentialsProvider;  
  12. import org.apache.http.client.methods.HttpUriRequest;  
  13. import org.apache.http.impl.auth.BasicSchemeFactory;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15.   
  16. /** 
  17.  * @author Administrator 
  18.  *  
  19.  */  
  20. public class HTTPBasicClient {  
  21.   
  22.     private URI serverURI = null;  
  23.     String response = null;  
  24.     private DefaultHttpClient httpClient = new DefaultHttpClient();  
  25.   
  26.     /** 
  27.      * constructor 
  28.      *  
  29.      */  
  30.     public HTTPBasicClient(String userName, String passWord, String url) {  
  31.         try {  
  32.             serverURI = new URI(url);  
  33.   
  34.             UsernamePasswordCredentials creds = new UsernamePasswordCredentials(  
  35.                     userName, passWord);  
  36.             CredentialsProvider credsProvider = httpClient  
  37.                     .getCredentialsProvider();  
  38.             credsProvider.setCredentials(new AuthScope(serverURI.getHost(),  
  39.                     serverURI.getPort()), (Credentials) creds);  
  40.             httpClient.getParams().setParameter(  
  41.                     AuthPolicy.AUTH_SCHEME_PRIORITY,  
  42.                     Collections.singleton(AuthPolicy.BASIC));  
  43.             httpClient.getAuthSchemes().register(AuthPolicy.BASIC,  
  44.                     new BasicSchemeFactory());  
  45.   
  46.         } catch (Exception e) {  
  47.               
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      * send request to server 
  53.      *  
  54.      * @param httpClient 
  55.      * @param httpUriRequest 
  56.      * @return response HttpResponse 
  57.      */  
  58.     public HttpResponse send(HttpUriRequest httpUriRequest) {  
  59.         HttpResponse response = null;  
  60.         try {  
  61.             if (null == httpClient) {  
  62.                   
  63.                 return response;  
  64.             }  
  65.             response = httpClient.execute(httpUriRequest);  
  66.   
  67.         } catch (Exception e) {  
  68.               
  69.         }  
  70.         return response;  
  71.     }  
  72.   
  73. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值