返回顶部
首页 > 资讯 > 后端开发 > JAVA >java操作new HttpPost(URL)和 new URL(shixun_ip) 获取流
  • 837
分享到

java操作new HttpPost(URL)和 new URL(shixun_ip) 获取流

java教程java 2020-06-13 16:06:52 837人浏览 绘本
摘要

HttpClient:private static HttpClient httpClient; static { if (httpClient == null) { HttpParams params = new BasicH

HttpClient:

private static HttpClient httpClient;
	static {
		if (httpClient == null) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			// 超时设置 
			ConnManagerParams.setTimeout(params, 1000);
			
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			
			HttpConnectionParams.setSoTimeout(params, 4000);
			SchemeReGIStry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));
			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			httpClient = new DefaultHttpClient(conMgr, params);
		}
	}
@SuppressWarnings("unchecked")
	private  T getJSONObjectFromUrl(String urlStr,
			List params, Class className) throws Exception{
		T object = null;
 
		InputStream in = null;
		try {
			HttpPost httpPost = new HttpPost(urlStr);
 
			if (params != null) {
				//				List nvps = new ArrayList();
				//				for (Entry entry : params.entrySet()) {
				//					nvps.add(new BasicNameValuePair(entry.geTKEy(), entry
				//							.getValue()));
				//				}
				httpPost.setEntity(new UrlEncodedFORMEntity(params, HTTP.UTF_8));
			}
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
 
			if(entity!=null){
				in= entity.getContent(); //之前没使用这个造成了大量异常抛出
			}
 
			
 
			String s = inputStream2String(in,"UTF-8");
			jsonResult jsonResult = (JsonResult)JSONObject.parseObject(s, JsonResult.class);
			if(jsonResult.getCode() == 200){
				Object obj = jsonResult.getData();
 
				if(obj != null){
					if(className.isInstance(obj)){
						object = (T)(obj);
					}
					else if(obj instanceof JSONObject){
						object= JSONObject.parseObject(obj.toString(), className);
					}					
				}
			}else{
				throw new Exception(jsonResult.getMsg());
			}
 
			if(in!=null){
				in.close();
			}
 
		} catch (Exception e) {
			throw e;
		}
 
		return object;
	}

new URL():

try{
					
					//省略
					URL shixun = new URL(url);
					InputStream in = shixun.openStream();
 
					
					long end = System.currentTimeMillis();  
					if((end-start)<=5000){  //5s内不响应就跳过
						
						String ret = cn.com.jsoft.jframe.utils.StringUtils.toString(in, "utf-8");
						JSONObject obj = JSONObject.fromObject(ret);
						if(obj!=null&&obj.getJSONObject("info")!=null&&obj.containsKey("info")==true){
							JSONObject info = obj.getJSONObject("info");
							JSONArray data = info.getJSONArray("data");
							if(data!=null&&data.size()>0){
								for(int i=0;i

java将InputStream转为String

public static String inputStream2String(InputStream is, String charset) {
		ByteArrayOutputStream baos = null;
 
		try {
			baos = new ByteArrayOutputStream();
			int i = -1;
			while ((i = is.read()) != -1) {
				baos.write(i);
			}
			return baos.toString(charset);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"
					+ e.getMessage());
		} finally {
			if (null != baos) {
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"
							+ e.getMessage());
				}
				baos = null;
			}
		}
 
		return null;
	}

--结束END--

本文标题: java操作new HttpPost(URL)和 new URL(shixun_ip) 获取流

本文链接: https://lsjlt.com/news/4110.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作