溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java操作new HttpPost(URL)和 new URL(shixun_ip) 獲取流的方法

發(fā)布時(shí)間:2020-10-13 17:48:46 來源:億速云 閱讀:1488 作者:小新 欄目:編程語言

java操作new HttpPost(URL)和 new URL(shixun_ip) 獲取流的方法?這個(gè)問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個(gè)問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!

HttpClient:

private static HttpClient httpClient;
	static {
		if (httpClient == null) {
			HttpParams params = new BasicHttpParams();
			// 設(shè)置一些基本參數(shù)
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			// 超時(shí)設(shè)置 /* 從連接池中取連接的超時(shí)時(shí)間 */
			ConnManagerParams.setTimeout(params, 1000);
			/* 連接超時(shí) */
			HttpConnectionParams.setConnectionTimeout(params, 2000);
			/* 請求超時(shí) */
			HttpConnectionParams.setSoTimeout(params, 4000);
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));
			// 使用線程安全的連接管理來創(chuàng)建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			httpClient = new DefaultHttpClient(conMgr, params);
		}
	}
@SuppressWarnings("unchecked")
	private <T> T getJsonObjectFromUrl(String urlStr,
			List<NameValuePair> params, Class<T> className) throws Exception{
		T object = null;
 
		InputStream in = null;
		try {
			HttpPost httpPost = new HttpPost(urlStr);
 
			if (params != null) {
				//				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				//				for (Entry<String, String> 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(); //之前沒使用這個(gè)造成了大量異常拋出
			}
 
			/*String s = EntityUtils.toString(in, "UTF-8");
			if (entity != null) {
				EntityUtils.consume(entity);
			}*/
 
			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{
					
<span style="white-space:pre">					</span>//省略
					URL shixun = new URL(url);
					InputStream in = shixun.openStream();
 
					
					long end = System.currentTimeMillis();  
					if((end-start)<=5000){  //5s內(nèi)不響應(yīng)就跳過
						
						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<data.size();i++){
									JSONObject entry = data.getJSONObject(i);
									
								}
							}
						}
						in.close();
					}
 
				}catch (Exception e) {
					e.printStackTrace();
				}

java將InputStream轉(zhuǎn)為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;
	}

感謝各位的閱讀!看完上述內(nèi)容,你們對java操作new HttpPost(URL)和 new URL(shixun_ip) 獲取流的方法大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI