1. 程式人生 > >HTTPClient獲取介面資料返回JSON

HTTPClient獲取介面資料返回JSON

public static String getDataJson(String url, Integer pageNo, Integer pageSize, String search) {
		HttpPost httpPost = null;
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();//設定請求和傳輸超時時間
			httpPost.setConfig(requestConfig);
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			list.add(new BasicNameValuePair("pageNo", pageNo.toString()));
			list.add(new BasicNameValuePair("pageSize", pageSize.toString()));
			list.add(new BasicNameValuePair("search", search));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"utf-8");
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);
			if(response != null){
				
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					return EntityUtils.toString(resEntity,"utf-8");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			
		}finally {
			httpPost.releaseConnection();
		}
		
		return "";
	}

將字串轉化為JSON取資料:

JSON.parseObject(httpResult.getResultString()).getJSONObject("result").getInteger("data")