`

javaeye api [java httpclient版] 简单封装

阅读更多
java 使用 httpclient 调用 javaeyeapi
------------------------------------------------------------

package com.javaeye.client;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class ClientUtils {
	/**
	 * 
	 * @param hostUrl 要请求的host name  如:http://api.iteye.com/api/twitters/list -> api.iteye.com
	 * @param getUrl  要请求的get url 	 如:http://api.iteye.com/api/twitters/list -> api/twitters/list
	 * @param userName	username
	 * @param password	password
	 * @return javaeye api 返回的son字符串
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static String getJsonContent(String hostUrl,String getUrl,String userName,String password) throws ClientProtocolException, IOException
	{
		String jsonStr="";
		
		DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(hostUrl, 80), 
                new UsernamePasswordCredentials(userName, password));

        BasicHttpContext localcontext = new BasicHttpContext();

        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        
        httpclient.addRequestInterceptor((HttpRequestInterceptor) new PreemptiveAuth(), 0);
         
        HttpHost targetHost = new HttpHost(hostUrl);

        HttpGet httpget = new HttpGet("/" + getUrl);
        
        HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {            
            jsonStr = EntityUtils.toString(entity);
            
            //System.out.println(jsonStr);            
            entity.consumeContent();
        }
                
        httpclient.getConnectionManager().shutdown(); 
		
		return jsonStr;
	}
	
	static class PreemptiveAuth implements HttpRequestInterceptor {

        public void process(
                final HttpRequest request, 
                final HttpContext context) throws HttpException, IOException {
            
            AuthState authState = (AuthState) context.getAttribute(
                    ClientContext.TARGET_AUTH_STATE);
            
            // If no auth scheme avaialble yet, try to initialize it preemptively
            if (authState.getAuthScheme() == null) {
                AuthScheme authScheme = (AuthScheme) context.getAttribute(
                        "preemptive-auth");
                CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                        ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(
                        ExecutionContext.HTTP_TARGET_HOST);
                if (authScheme != null) {
                    Credentials creds = credsProvider.getCredentials(
                            new AuthScope(
                                    targetHost.getHostName(), 
                                    targetHost.getPort()));
                    if (creds == null) {
                        throw new HttpException("No credentials for preemptive authentication");
                    }
                    authState.setAuthScheme(authScheme);
                    authState.setCredentials(creds);
                }
            }
            
        }
        
    }
}



/******************************************************************/
test
package com.javaeye.client;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

public class TestClientUtils {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str=null;
		try {
			str = ClientUtils.getJsonContent("api.iteye.com", "api/twitters/list", "msnvip", "×××××");
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str);
	}

}



我还是抛砖;请有时间的同学继续深度挖掘;
附件一:eclipse中 简单封装的源代码
附件二:httpclient4.02
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics