java HttpClient在客户端处理service服务数据解决方案一例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.log4j.Logger;

import com.tjsoft.util.StringUtil;

public class ClientUtil {
	private static Logger log = Logger.getLogger(ClientUtil.class);

	/**
	 * 登录 获取token
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String login() throws Exception {
		log.info("info:"+new Date().toLocaleString()+"开始执行" + ClientUtil.class + "类 login()方法.");
		String url = ServiceUrlUtil.LOGIN;
		String json = "{\"loginId\":\"" + ServiceUrlUtil.SERVICE_LOGINID.trim()
				+ "\"," + "\"password\":\""
				+ ServiceUrlUtil.SERVICE_PASSWORD.trim() + "\","
				+ "\"auth_key\":\"" + ServiceUrlUtil.SERVICE_AUTHKEY.trim()
				+ "\"" + "}";
		//System.out.println("json----------------->"+json);
		String result = requestForStringUsePost(url, json);
		//System.out.println("result----------------->"+result);
		String eCode = JSONObject.fromObject(result).getString("eCode");
		String eMsg = JSONObject.fromObject(result).getString("eMsg");
		String token = JSONObject.fromObject(result).getString("token");
		//System.out.println("eCode----->"+eCode+",eMsg---------->"+eMsg+",token------------->"+token);
		log.info("info:"+new Date().toLocaleString()+"执行" + ClientUtil.class + "类 login()方法:" + eCode + "-"
				+ eMsg + ",返回值:" + token);
		return token;
	}

	/**
	 * 注销登录
	 * 
	 * @param access_token
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String logout(String token) throws Exception {
		log.info("info:"+new Date().toLocaleString()+"开始执行" + ClientUtil.class + "类 login()方法.");
		String url = ServiceUrlUtil.LOGOUT+"?token="+token;
		String result = ClientUtil.requestForStringUseGet(url);
		String eCode = JSONObject.fromObject(result).get("eCode").toString();
		String eMsg = JSONObject.fromObject(result).get("eMsg").toString();
		//System.out.println("eCode----->"+eCode+",eMsg---------->"+eMsg);
		log.info("info:"+new Date().toLocaleString()+"执行" + ClientUtil.class + "类 logout()方法:" + eCode + "-"
				+ eMsg + ".");
		return result;
	}

	/**
	 * 这里需要传入机构ID 查询机构下的窗口的时候 需要传入该机构编号 然后返回accessToken
	 * 
	 * @throws Exception
	 */
	/*
	 * public static String getSessionOrgCode(String orgCode) throws Exception {
	 * String url = "http://sxsl.sz.gov.cn/sxgl/c/api.pmi/login"; String json = "
	 * {\"key\":\"" + ServiceUrlUtil.APP_KEY + "\",\"secret\":\"" +
	 * ServiceUrlUtil.APP_SECRET + "\",\"loginname\":\"" +
	 * ServiceUrlUtil.ACCOUNT + "\", " + " \"pwd\":\"" + ServiceUrlUtil.PASSWORD +
	 * "\",\"dept\":\"" + orgCode + "\"}"; String result =
	 * ClientUtil.requestForStringUsePost(url, json); Object data =
	 * JSONObject.fromObject(result).get("data"); String access_token ="";
	 * if(data!=null){ access_token =
	 * JSONObject.fromObject(data).getString("access_token"); } return
	 * access_token; }
	 */

	/**
	 * 调用http请求,返回string结果数据
	 * 
	 * @param req
	 *            json格式请求参数
	 * @param fi
	 * @return
	 */
	public static String requestForStringUseGet(String url) throws Exception {
		String returnStr = "";
		HttpResponse httpResponse = null;
		DefaultHttpClient httpClient = null;
		httpClient = new DefaultHttpClient();// http客户端
		enableSSL(httpClient);

		httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
				false);
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(ServiceUrlUtil.TIME_OUT.trim()));

		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

		// 请求地址
		HttpGet httpget = new HttpGet(url);

		@SuppressWarnings("unused")
		Date sDate = new Date();
		httpResponse = httpClient.execute(httpget);
		// 请求结果处理
		HttpEntity entity = httpResponse.getEntity();

		if (entity != null) {
			InputStream content = entity.getContent();
			returnStr = convertStreamToString(content);
		}
		// 释放连接
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
		return returnStr;

	}

	/**
	 * 调用http请求,返回string结果数据
	 * 
	 * @param req
	 *            json格式请求参数
	 * @param fi
	 * @return
	 */
	public static String requestForStringUsePost(String url, String json)
			throws Exception {
		String returnStr = "";
		HttpResponse httpResponse = null;
		DefaultHttpClient httpClient = null;

		@SuppressWarnings("unused")
		Date sDate = new Date();

		// 请求参数
		httpClient = new DefaultHttpClient();// http客户端
		enableSSL(httpClient);
		httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
				false);
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(ServiceUrlUtil.TIME_OUT.trim()));

		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000);
		httpClient.getParams().setParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		// 请求地址
		HttpPost httppost = new HttpPost(url);
		if (StringUtil.isNotBlank(json)) {
			StringEntity stringEntity = new StringEntity(json, "utf-8");
			httppost.setEntity(stringEntity);
		} else {
			StringEntity stringEntity = new StringEntity("{}", "utf-8");
			httppost.setEntity(stringEntity);
		}
		httppost.setHeader("Content-type", "application/json");
		httpResponse = httpClient.execute(httppost);
		// 请求结果处理
		HttpEntity entity = httpResponse.getEntity();

		if (entity != null) {
			InputStream content = entity.getContent();
			returnStr = convertStreamToString(content);
		}

		// 释放连接
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
		return returnStr;
	}

	/**
	 * 将流转换为字符串
	 * 
	 * @param is
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String convertStreamToString(InputStream is)
			throws UnsupportedEncodingException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				"utf-8"));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@SuppressWarnings("deprecation")
	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 {

		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

	};

	/**
	 * 测试
	 * 
	 * @Description: TODO
	 * @param args
	 *            void
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws Exception {
		ClientUtil util = new ClientUtil();
		String token = util.login();
		System.out.println(token);
		//String token = "VCRt853rOjH_aHh-1-fLLOQdW-wcu-pyLh2LT3jjP2cJ3SCF1qDp!-366310036!1384824151531";
		util.logout(token);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答:使用Apache HttpClient可以实现这一目标。首先,你需要创建一个HttpClient实例,并配置它以支持大量数据传输。然后,使用HttpClient的execute方法,创建一个HttpPost对象,并将要传输的数据设置到HttpPost对象中,最后调用HttpClient的execute方法,发出HTTP请求,实现数据的传输。 ### 回答2: 在Java中,可以使用Apache HttpClient库来进行HTTP请求和响应的操作。下面是使用Java接口httpclient传输大量数据的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import java.io.*; import java.util.ArrayList; import java.util.List; public class HttpClientExample { public static void main(String[] args) { String url = "http://example.com/post"; List<String> data = getData(); // 假设data为大量数据的集合 try { HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(data)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } client.getConnectionManager().shutdown(); } catch (IOException e) { e.printStackTrace(); } } private static List<String> getData() { List<String> data = new ArrayList<>(); // 添加大量数据到data中 return data; } } ``` 上述代码使用ApacheHttpClient库创建了一个HttpClient实例,并通过HttpPost方法发送POST请求到指定的URL。使用`setEntity()`方法将数据添加到POST请求中。在本例中,使用`new UrlEncodedFormEntity(data)`将数据以表单编码的方式添加到请求中。如果数据JSON格式的,可以使用`new StringEntity(data, ContentType.APPLICATION_JSON)`将数据作为JSON字符串添加到请求中。 执行POST请求后,通过获取响应的实体`HttpResponse.getEntity()`,可以得到服务器返回的数据。在本例中,使用`getContent()`方法获取输入流,并通过BufferedReader以行的形式读取返回的数据。 最后,最好在使用完HttpClient之后调用`client.getConnectionManager().shutdown()`方法释放相关的资源。 需要注意的是,传输大量数据时可能会遇到一些问题,例如超时、内存不足等。可以根据实际情况调整HttpClient的参数和配置,以确保传输过程的稳定性和性能。 ### 回答3: 在Java中使用HttpClient传输大量数据可以按照以下步骤进行: 1. 引入HttpClient库:首先,在Java工程中引入HttpClient库。可以通过在pom.xml文件中添加相应的依赖项来导入。 2. 创建HttpClient对象:使用HttpClientBuilder类创建一个HttpClient对象,该对象将用于发送HTTP请求。 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建HttpPost请求:创建一个HttpPost请求对象,并设置请求的URL和其他头部信息。如果有需要,还可以设置代理、身份验证、连接超时等。 ```java HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(jsonData)); ``` 4. 设置请求体:如果需要发送大量数据,可以将数据作为请求体传递。可以使用StringEntity、FileEntity等类来设置请求体。 ```java httpPost.setEntity(new StringEntity(data, ContentType.TEXT_PLAIN)); ``` 5. 发送请求并获取响应:通过执行HttpPost请求对象发送请求,并获取响应对象。可以使用CloseableHttpResponse类来接收响应。 ```java CloseableHttpResponse response = httpClient.execute(httpPost); ``` 6. 解析响应:从响应对象中获取相应的数据,可以通过EntityUtils类将响应体转换为字符串。 ```java HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); ``` 7. 关闭连接:使用完毕后,需要关闭连接和释放资源。 ```java response.close(); httpClient.close(); ``` 以上是使用HttpClient传输大量数据的基本步骤。根据实际需求,可能还需要处理异常、设置重试机制、添加请求头等其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值