Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的Java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

三、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams
params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity
entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String

name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

四、实例

package com.test;  

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test; public class HttpClientTest { @Test
public void jUnitTest() {
get();
} /**
* HttpClient连接SSL
*/
public void ssl() {
CloseableHttpClient httpclient = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
try {
// 加载keyStore d:\\tomcat.keystore
trustStore.load(instream, "123456".toCharArray());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
// 相信自己的CA和所有自签名的证书
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 创建http请求(get方式)
HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
}
} finally {
response.close();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} finally {
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} /**
* post方式提交表单(模拟用户登录请求)
*/
public void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/
public void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("type", "house"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 发送 get请求
*/
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 上传文件
*/
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action"); FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

五、实例(开发用到工具类实例)

package com.fh.util.http;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import net.sf.json.JSONObject; /**
* @className:HttpClientUtil.java
* @classDescription:HttpClient工具类//待完善模拟登录,cookie,证书登录
* @author:xiayingjie
* @createTime:2011-8-31
*/ public class HttpClientUtilMy { public static String CHARSET_ENCODING = "UTF-8";
// private static String
// USER_AGENT="Mozilla/4.0 (compatible; MSIE 6.0; Win32)";//ie6
public static String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 7.0; Win32)";// ie7 // private static String
// USER_AGENT="Mozilla/4.0 (compatible; MSIE 8.0; Win32)";//ie8 /**
* 获取DefaultHttpClient对象
*
* @param charset
* 字符编码
* @return DefaultHttpClient对象
*/
private static DefaultHttpClient getDefaultHttpClient(final String charset) {
DefaultHttpClient httpclient = new DefaultHttpClient();
// 模拟浏览器,解决一些服务器程序只允许浏览器访问的问题
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
httpclient.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
charset == null ? CHARSET_ENCODING : charset); // 浏览器兼容性
httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
// 定义重试策略
httpclient.setHttpRequestRetryHandler(requestRetryHandler); return httpclient;
} /**
* 访问https的网站
*
* @param httpclient
*/
private static void enableSSL(DefaultHttpClient httpclient) {
// 调用ssl
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 重写验证方法,取消检测ssl
*/
private static TrustManager truseAllManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub } public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
} }; /**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试3次
if (executionCount >= 3) {
// 如果连接次数超过了最大值则停止重试
return false;
}
if (exception instanceof NoHttpResponseException) {
// 如果服务器连接失败重试
return true;
}
if (exception instanceof SSLHandshakeException) {
// 不要重试ssl连接异常
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// 重试,如果请求是考虑幂等
return true;
}
return false;
}
}; /**
* 使用ResponseHandler接口处理响应,HttpClient使用ResponseHandler会自动管理连接的释放,解决了对连接的释放管理
*/
private static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
// 自定义响应处理
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
String charset = EntityUtils.getContentCharSet(entity) == null ? CHARSET_ENCODING
: EntityUtils.getContentCharSet(entity);
return new String(EntityUtils.toByteArray(entity), charset);
} else {
return null;
}
}
}; /**
* 使用post方法获取相关的数据
*
* @param url
* @param paramsList
* @return
*/
public static String post(String url, List<NameValuePair> paramsList) {
return httpRequest(url, paramsList, "POST", null);
} /**
* 使用post方法并且通过代理获取相关的数据
*
* @param url
* @param paramsList
* @param proxy
* @return
*/
public static String post(String url, List<NameValuePair> paramsList, HttpHost proxy) {
return httpRequest(url, paramsList, "POST", proxy);
} /**
* 使用get方法获取相关的数据
*
* @param url
* @param paramsList
* @return
*/
public static String get(String url, List<NameValuePair> paramsList) {
return httpRequest(url, paramsList, "GET", null);
} /**
* 使用get方法并且通过代理获取相关的数据
*
* @param url
* @param paramsList
* @param proxy
* @return
*/
public static String get(String url, List<NameValuePair> paramsList, HttpHost proxy) {
return httpRequest(url, paramsList, "GET", proxy);
} /**
* 提交数据到服务器
*
* @param url
* @param params
* @param authenticated
* @throws IOException
* @throws ClientProtocolException
*/
public static String httpRequest(String url, List<NameValuePair> paramsList, String method, HttpHost proxy) {
String responseStr = null;
// 判断输入的值是是否为空
if (null == url || "".equals(url)) {
return null;
} // 创建HttpClient实例
DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING); // 判断是否是https请求
if (url.startsWith("https")) {
enableSSL(httpclient);
}
String formatParams = null;
// 将参数进行utf-8编码
if (null != paramsList && paramsList.size() > 0) {
formatParams = URLEncodedUtils.format(paramsList, CHARSET_ENCODING);
}
// 如果代理对象不为空则设置代理
if (null != proxy) {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
try {
// 如果方法为Get
if ("GET".equalsIgnoreCase(method)) {
if (formatParams != null) {
url = (url.indexOf("?")) < 0 ? (url + "?" + formatParams)
: (url.substring(0, url.indexOf("?") + 1) + formatParams);
}
HttpGet hg = new HttpGet(url);
responseStr = httpclient.execute(hg, responseHandler); // 如果方法为Post
} else if ("POST".equalsIgnoreCase(method)) {
HttpPost hp = new HttpPost(url);
if (formatParams != null) {
StringEntity entity = new StringEntity(formatParams);
entity.setContentType("application/x-www-form-urlencoded");
hp.setEntity(entity);
}
responseStr = httpclient.execute(hp, responseHandler); } } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseStr;
} /**
* 提交数据到服务器
*
* @param url
* @param params
* @param authenticated
* @throws IOException
* @throws ClientProtocolException
*/
public static String httpFileRequest(String url, Map<String, String> fileMap, Map<String, String> stringMap,
int type, HttpHost proxy) {
String responseStr = null;
// 判断输入的值是是否为空
if (null == url || "".equals(url)) {
return null;
}
// 创建HttpClient实例
DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING); // 判断是否是https请求
if (url.startsWith("https")) {
enableSSL(httpclient);
} // 如果代理对象不为空则设置代理
if (null != proxy) {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
// 发送文件
HttpPost hp = new HttpPost(url);
MultipartEntity multiEntity = new MultipartEntity();
try {
// type=0是本地路径,否则是网络路径
if (type == 0) {
for (String key : fileMap.keySet()) {
multiEntity.addPart(key, new FileBody(new File(fileMap.get(key))));
}
} else {
for (String key : fileMap.keySet()) {
multiEntity.addPart(key, new ByteArrayBody(getUrlFileBytes(fileMap.get(key)), key));
}
}
// 加入相关参数 默认编码为utf-8
for (String key : stringMap.keySet()) {
multiEntity.addPart(key, new StringBody(stringMap.get(key), Charset.forName(CHARSET_ENCODING)));
}
hp.setEntity(multiEntity);
responseStr = httpclient.execute(hp, responseHandler);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseStr;
} /**
* 将相关文件和参数提交到相关服务器
*
* @param url
* @param fileMap
* @param StringMap
* @return
*/
public static String postFile(String url, Map<String, String> fileMap, Map<String, String> stringMap) {
return httpFileRequest(url, fileMap, stringMap, 0, null);
} /**
* 将相关文件和参数提交到相关服务器
*
* @param url
* @param fileMap
* @param StringMap
* @return
*/
public static String postUrlFile(String url, Map<String, String> urlMap, Map<String, String> stringMap) {
return httpFileRequest(url, urlMap, stringMap, 1, null);
} /**
* 获取网络文件的字节数组
*
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws ClientProtocolException
* @throws IOException
*/
public static byte[] getUrlFileBytes(String url) throws ClientProtocolException, IOException { byte[] bytes = null;
// 创建HttpClient实例
CloseableHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);
// 获取url里面的信息
HttpGet hg = new HttpGet(url);
HttpResponse hr = httpclient.execute(hg);
bytes = EntityUtils.toByteArray(hr.getEntity());
// 转换内容为字节
return bytes;
} /**
* 获取图片的字节数组
*
* @createTime 2011-11-24
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws ClientProtocolException
* @throws IOException
*/
public static byte[] getImg(String url) throws ClientProtocolException, IOException {
byte[] bytes = null;
// 创建HttpClient实例
DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);
// 获取url里面的信息
HttpGet hg = new HttpGet(url);
HttpResponse hr = httpclient.execute(hg);
bytes = EntityUtils.toByteArray(hr.getEntity());
// 转换内容为字节
return bytes;
} /**
* @Description 请求微吼接口
* @author 张洋
* @date 2017年8月12日 上午11:19:44
* @param method
* 方法名 样式:{资源名}/{函数名}
* @param params 条件参数
* @return
*/
public static JSONObject getVhallUrlByPost(String method, Map<String,String> param) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
//封装请求参数
for (Entry<String, String> entry : param.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
}
// 访问接口地址
Object[] parameter = new Object[4];
parameter[0] = method;
String url = MessageFormat.format("http://e.vhall.com/api/vhallapi/v2/{0}", parameter);
// String url = MessageFormat.format("http:loaclhost/{0}", parameter);
// 参数
// List<NameValuePair> params = new ArrayList<NameValuePair>();
// 添加公共参数
params.add(new BasicNameValuePair("auth_type", "1"));
params.add(new BasicNameValuePair("account", "v19462836"));
params.add(new BasicNameValuePair("password", "12345678"));
String str = HttpClientUtilMy.post(url, params);
JSONObject jsonData = JSONObject.fromObject(str);
System.out.println("code:" + jsonData.get("code"));
System.out.println("info:" + jsonData.get("msg"));
System.out.println(jsonData.toString());
return jsonData; } }

HttpClient使用详解 (一)的更多相关文章

  1. HttpClient使用详解(转)

     HttpClient使用详解 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户 ...

  2. HttpClient使用详解

    http://itindex.net/detail/52566-httpclient HttpClient使用详解 标签: httpclient | 发表时间:2015-01-22 12:07 | 作 ...

  3. Java进阶(三十二) HttpClient使用详解

    Java进阶(三十二) HttpClient使用详解 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们 ...

  4. gvoory脚本中关于HttpClient使用详解实例

    一.gvoory脚本中关于HttpClient使用详解实例 HttpClient:是一个接口 首先需要先创建一个DefaultHttpClient的实例 HttpClient httpClient=n ...

  5. HttpClient请求详解

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

  6. HttpClient类详解

    文章链接:https://blog.csdn.net/justry_deng/article/details/81042379 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了 ...

  7. 转载:HttpClient使用详解

    原文地址:http://blog.csdn.net/wangpeng047/article/details/19624529 Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自 ...

  8. [转]HttpClient使用详解

    Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...

  9. Asp.Net MVC WebAPI的创建与前台Jquery ajax后台HttpClient调用详解

    1.什么是WebApi,它有什么用途? Web API是一个比较宽泛的概念.这里我们提到Web API特指ASP.NET MVC Web API.在新出的MVC中,增加了WebAPI,用于提供REST ...

随机推荐

  1. 2、RabbitMQ-simplest thing(简单队列)

    1.项目准备: 使用maven的依赖 <dependencies> <dependency> <groupId>com.rabbitmq</groupId&g ...

  2. mvc4中viewbag viewdata 和 tempdata的区别

    ViewBag 不再是字典的键值对结构,而是 dynamic 动态类型,它会在程序运行的时候动态解析. eg: ViewBag.NumberObjs = new string[] { "on ...

  3. Java对象声明时:new与null的区别

    作者:林子云链接:https://www.zhihu.com/question/21468505/answer/18333632来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  4. disconf实践(二)基于XML的分布式配置文件管理,不会自动reload

    上一篇博文介绍了disconf web的搭建流程,这一篇就介绍disconf client通过配置xml文件来获取disconf管理端的配置信息. 1. 登录管理端,并新建APP,然后上传配置文件 2 ...

  5. HDU 1102(Constructing Roads)(最小生成树之prim算法)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1102 Constructing Roads Time Limit: 2000/1000 MS (Ja ...

  6. Ubuntu 编译出现 ISO C++ 2011 不支持的解决办法

    问题 在编译时出现如下error: error:This file requires compiler and library support for the ISO C++ 2011 standar ...

  7. 大话Linux内核中锁机制之原子操作、自旋锁

    转至:http://blog.sina.com.cn/s/blog_6d7fa49b01014q7p.html 很多人会问这样的问题,Linux内核中提供了各式各样的同步锁机制到底有何作用?追根到底其 ...

  8. Kafka个人总结

    Kafka 应对场景:消息持久化.吞吐量是第一要求.状态由客户端维护.必须是分布式的.Kafka 认为 broker 不应该阻塞生产者,高效的磁盘顺序读写能够和网络 IO 一样快,同时依赖现代 OS ...

  9. Xcode 创建 支持IOS4.3以上版本的应用的方法

    如果是Xcode 5的话步骤为 点击项目名称->Build Settings->搜索 Architectures 这个里面的原始的值是Standard architectures(armv ...

  10. iOS 百度地图判断用户是否拖动地图的检测方法

    前言:百度地图API并没有提供移动地图时的回调接口 实现:通过判断当前地图的中心位置是否为用户位置来判断,代码如下 -(void)mapView:(BMKMapView *)mapView regio ...