httpCLient 4.2 实现basic认证
httclient的实现basic认证的方式,和以前的版本不同。形式如下
public static String setSetting1() throws ClientProtocolException, IOException, URISyntaxException
{
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("i2.api.weibo.com"));
String url ="http://xxxxx/2/common/apps/set_settings.json";
URI uri = new URI("http://xxxxxx/common/apps/set_settings.json");
client.getCredentialsProvider().setCredentials( new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials("15810336966", "kobe1392936"));
HttpPost post = new HttpPost(url);
List <NameValuePair> params = new ArrayList <NameValuePair>();
params.add(new BasicNameValuePair("source", "2975945008"));
params.add(new BasicNameValuePair("item_id", "2"));
params.add(new BasicNameValuePair("settings", "[{"name":"sky"}]"));
HttpHost host = new HttpHost(uri.getHost(),uri.getPort(),"http");
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
// Add AuthCache to the execution context
//uri.getHost();
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
"UTF8");
post.setEntity(entity);
// client.execute(post);
// HttpResponse response =client.execute(post);
HttpResponse response = client.execute(host, post, localcontext);
//HttpResponse response =client.execute(post)
//System.out.println(url);
System.out.println("set "+EntityUtils.toString(response.getEntity()));
return null;
}