依赖
<!-- 聚合数据API SDK -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
Controller层
package com.cloud.controller;
import com.alibaba.fastjson.JSONArray;
import com.cloud.domain.Stock;
import com.cloud.domain.Stockdata;
import com.cloud.domain.Stockdatatwo;
import com.cloud.service.StockdataService;
import com.cloud.service.StockdatatwoService;
import com.cloud.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 聚合数据提取类
*/
@Api(tags = "聚合数据提取")
@RequestMapping("/extract")
@RestController
@CrossOrigin
public class DataExtractController {
@Autowired
StockdataService stockdataService;
@Autowired
StockdatatwoService stockdatatwoService;
/**
* 调用远程聚合数据接口API 提取沪股列表数据
*
* @return
*/
@ApiOperation(value = "提取沪股列表", notes = "聚合数据提取")
@GetMapping("/shall")
public R shall() {
// 发送http请求的url 沪股列表shall 深圳股市列表szall 香港股市列表hkall
String url = "http://web.juhe.cn/finance/stock/shall";
Map<String, String> params = new HashMap<String, String>();
params.put("key", "fc1809d7cc998935f1a7e7ca341be406"); // 在个人中心->我的数据,接口名称上方查看
params.put("gid", "sh601010"); // 股票编号,上海股市以sh开头,深圳股市以sz开头如:sh601009
String paramsStr = urlencode(params);
System.out.println(paramsStr);
String response = doGet(url, paramsStr);
// 输出请求结果
System.out.println(response);
JSONObject jsonObject = null;
try {
// 解析请求结果,json:
jsonObject = JSONObject.fromObject(response);
//转换json对象 解析 JSON 响应,并将解析后的数据存储到数据库
com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(response);//将 JSON 字符串 response 解析为 JSONObject 对象。
com.alibaba.fastjson.JSONObject result = jsonObject1.getJSONObject("result");//从 jsonObject1 中获取名为 "result" 的 JSONObject 对象。
JSONArray data = result.getJSONArray("data");//从 "result" 对象中获取名为 "data" 的 JSONArray 对象。
ArrayList<Stockdata> objects = new ArrayList<>();
//遍历 "data" 数组中的每个元素。
for (int i = 0; i < data.size(); i++) {
Stockdata quotes = new Stockdata();
//在循环中,通过 data.getJSONObject(i) 获取每个股票数据的 JSONObject 对象,
// 并使用 jsonData.getString("key")、jsonData.getBigDecimal("key")、jsonData.getInteger("key") 等方法从中提取具体的字段值。
com.alibaba.fastjson.JSONObject jsonData = data.getJSONObject(i);
stockdataService.createData(jsonData.getString("symbol"));
quotes.setSymbol(jsonData.getString("symbol"));
quotes.setName(jsonData.getString("name"));
quotes.setTrade(jsonData.getBigDecimal("trade"));
quotes.setPricechange(jsonData.getBigDecimal("pricechange"));
quotes.setChangepercent(jsonData.getBigDecimal("changepercent"));
quotes.setBuy(jsonData.getBigDecimal("buy"));
quotes.setSell(jsonData.getBigDecimal("sell"));
quotes.setSettlement(jsonData.getBigDecimal("settlement"));
quotes.setOpen(jsonData.getBigDecimal("open"));
quotes.setHigh(jsonData.getBigDecimal("high"));
quotes.setLow(jsonData.getBigDecimal("low"));
quotes.setVolume(jsonData.getInteger("volume"));
quotes.setAmount(jsonData.getInteger("amount"));
quotes.setCode(jsonData.getInteger("code"));
quotes.setTicktime(jsonData.getString("ticktime"));
Date date = new Date();
quotes.setCreatetime(date);
//将每个股票数据对象添加到 ArrayList<Stockdata> 中。
objects.add(quotes);
//将股票数据对象保存到数据库中,通过调用 stockdataService 的 add() 方法实现。
stockdataService.add(quotes);
}
stockdataService.saveBatch(objects);
// 具体返回示例值,参考返回参数说明、json返回示例
System.out.println("jsonObject: " + jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
return R.success(jsonObject);
}
/**
* 调用远程聚合数据接口API 提取深圳股市列表数据
*
* @return
*/
@ApiOperation(value = "提取深圳股市列表",notes = "提取聚合数据")
@GetMapping("/szall")
public R szall() {
// 发送http请求的url 沪股列表shall 深圳股市列表szall 香港股市列表hkall
String url = "http://web.juhe.cn/finance/stock/szall";
Map<String, String> params = new HashMap<String, String>();
params.put("key", "fc1809d7cc998935f1a7e7ca341be406"); // 在个人中心->我的数据,接口名称上方查看
params.put("gid", "sz300001"); // 股票编号,上海股市以sh开头,深圳股市以sz开头如:sh601009
String paramsStr = urlencode(params);
System.out.println(paramsStr);
String response = doGet(url, paramsStr);
// 输出请求结果
System.out.println(response);
JSONObject jsonObject = null;
try {
// 解析请求结果,json:
jsonObject = JSONObject.fromObject(response);
//转换json对象
com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(response);
com.alibaba.fastjson.JSONObject result = jsonObject1.getJSONObject("result");
JSONArray data = result.getJSONArray("data");
ArrayList<Stockdatatwo> objects = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
Stockdatatwo stockdatatwo = new Stockdatatwo();
com.alibaba.fastjson.JSONObject jsonData = data.getJSONObject(i);
// stockdatatwoService.createDttatwo(jsonData.getString("symbol"));
stockdatatwo.setSymbol(jsonData.getString("symbol"));
stockdatatwo.setName(jsonData.getString("name"));
stockdatatwo.setTrade(jsonData.getBigDecimal("trade"));
stockdatatwo.setPricechange(jsonData.getBigDecimal("pricechange"));
stockdatatwo.setChangepercent(jsonData.getBigDecimal("changepercent"));
stockdatatwo.setBuy(jsonData.getBigDecimal("buy"));
stockdatatwo.setSell(jsonData.getBigDecimal("sell"));
stockdatatwo.setSettlement(jsonData.getBigDecimal("settlement"));
stockdatatwo.setOpen(jsonData.getBigDecimal("open"));
stockdatatwo.setHigh(jsonData.getBigDecimal("high"));
stockdatatwo.setLow(jsonData.getBigDecimal("low"));
stockdatatwo.setVolume(jsonData.getInteger("volume"));
stockdatatwo.setAmount(jsonData.getInteger("amount"));
stockdatatwo.setTicktime(jsonData.getString("ticktime"));
objects.add(stockdatatwo);
// stockdatatwoService.add(stockdatatwo);
}
stockdatatwoService.saveBatch(objects);
// 具体返回示例值,参考返回参数说明、json返回示例
System.out.println("jsonObject: " + jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
return R.success(jsonObject);
}
// 将map型转为请求参数型
public static String urlencode(Map<String, String> data) {
//创建一个StringBuilder对象sb,用于构建URL编码字符串。
StringBuilder sb = new StringBuilder();
//使用for循环遍历data中的每一对键值对。
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* get方式的http请求
*
* @param httpUrl 请求地址
* @param paramStr 请求参数
* @return 返回结果
*/
public static String doGet(String httpUrl, String paramStr) {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
String result = null;// 返回结果字符串
try {
httpUrl += "?" + paramStr;
// 创建远程url连接对象
URL url = new URL(httpUrl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 封装输入流,并指定字符集
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();// 关闭远程连接
}
}
return result;
}
/**
* post方式的http请求
*
* @param httpUrl 请求地址
* @param paramStr 请求参数
* @return 返回结果
*/
public static String doPost(String httpUrl, String paramStr) {
HttpURLConnection connection = null;
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 通过连接对象获取一个输出流
outputStream = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
outputStream.write(paramStr.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
}
serviceImpl
@Autowired
StockdataMapper stockdataMapper;
@Override
public void createData(String symbol) {
baseMapper.createData("stockdata_"+symbol);
}
Mapper.xml
<select id="createData">
CREATE TABLE if not exists ${s} (
`symbol` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`name` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`trade` DECIMAL(10, 3) DEFAULT NULL,
`pricechange` DECIMAL(10, 3) DEFAULT NULL,
`changepercent` DECIMAL(10, 3) DEFAULT NULL,
`buy` DECIMAL(10, 3) DEFAULT NULL,
`sell` DECIMAL(10, 3) DEFAULT NULL,
`settlement` DECIMAL(10, 3) DEFAULT NULL,
`open` DECIMAL(10, 3) DEFAULT NULL,
`high` DECIMAL(10, 3) DEFAULT NULL,
`low` DECIMAL(10, 3) DEFAULT NULL,
`volume` BIGINT DEFAULT NULL,
`amount` BIGINT DEFAULT NULL,
`code` INT DEFAULT NULL,
`ticktime` VARCHAR(100) DEFAULT NULL,
`per` DECIMAL(10, 3) DEFAULT NULL,
`pb` DECIMAL(10, 3) DEFAULT NULL,
`mktcap` DECIMAL(20, 3) DEFAULT NULL,
`nmc` DECIMAL(20, 3) DEFAULT NULL,
`turnoverratio` DECIMAL(10, 5) DEFAULT NULL,
`createtime` TIMESTAMP DEFAULT NULL,
PRIMARY KEY (`symbol`),
INDEX `code_index` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
</select>
<insert id="add">
INSERT INTO stockdata2_${symbol} (symbol, name, trade, pricechange, changepercent, buy, sell, settlement, open, high, low, volume, amount, code, ticktime, per, pb, mktcap, nmc, turnoverratio, createtime)
SELECT * FROM (SELECT #{symbol} as symbol, #{name} as name, #{trade} as trade, #{pricechange} as pricechange, #{changepercent} as changepercent, #{buy} as buy, #{sell} as sell, #{settlement} as settlement, #{open} as open, #{high} as high, #{low} as low, #{volume} as volume, #{amount} as amount, #{code} as code, #{ticktime} as ticktime, #{per} as per, #{pb} as pb, #{mktcap} as mktcap, #{nmc} as nmc, #{turnoverratio} as turnoverratio, #{createtime} as createtime) AS tmp
WHERE NOT EXISTS (
SELECT * FROM stockdata_${symbol}
WHERE DATE(createtime) = DATE(#{createtime})
);
</insert>
java代码自动分表
Controller
package com.cloud.controller;
import com.alibaba.fastjson.JSONArray;
import com.cloud.domain.Stockdata;
import com.cloud.service.StockdataService;
import com.cloud.service.StockdatatwoService;
import com.cloud.utils.R;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("fen")
public class FenController {
// 数据库连接参数
private static final String DB_URL = "jdbc:mysql://localhost:3306/day0402";
private static final String USER = "root";
private static final String PASS = "1234";
// 分表前缀
private static final String TABLE_PREFIX = "stockdata2_";
// 分表数量
private static final int NUM_TABLES = 50;
@Autowired
StockdataService stockdataService;
@Autowired
StockdatatwoService stockdatatwoService;
/**
* 调用远程聚合数据接口API 提取沪股列表数据
*
* @return
*/
@ApiOperation(value = "提取沪股列表", notes = "聚合数据提取")
@GetMapping("/shall")
public R shall() {
// 发送http请求的url 沪股列表shall 深圳股市列表szall 香港股市列表hkall
String url = "http://web.juhe.cn/finance/stock/shall";
Map<String, String> params = new HashMap<String, String>();
params.put("key", "fc1809d7cc998935f1a7e7ca341be406"); // 在个人中心->我的数据,接口名称上方查看
params.put("gid", "sh601010"); // 股票编号,上海股市以sh开头,深圳股市以sz开头如:sh601009
String paramsStr = urlencode(params);
System.out.println(paramsStr);
String response = doGet(url, paramsStr);
// 输出请求结果
System.out.println(response);
JSONObject jsonObject = null;
try {
// 解析请求结果,json:
jsonObject = JSONObject.fromObject(response);
//转换json对象
com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(response);
com.alibaba.fastjson.JSONObject result = jsonObject1.getJSONObject("result");
JSONArray data = result.getJSONArray("data");
ArrayList<Stockdata> objects = new ArrayList<>();
// 创建数据库连接
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement()) {
for (int i = 0; i < data.size(); i++) {
Stockdata quotes = new Stockdata();
com.alibaba.fastjson.JSONObject jsonData = data.getJSONObject(i);
// stockdataService.createData(jsonData.getString("symbol"));
String tableName = TABLE_PREFIX + jsonData.getString("symbol");
String createTableSQL = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
+ "symbol VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,"
+ "name VARCHAR(255) NOT NULL,"
+ "trade DECIMAL(10, 3) DEFAULT NULL,"
+ "pricechange DECIMAL(10, 3) DEFAULT NULL,"
+ "changepercent DECIMAL(10, 3) DEFAULT NULL,"
+ "buy DECIMAL(10, 3) DEFAULT NULL,"
+"sell DECIMAL(10, 3) DEFAULT NULL,"
+ "settlement DECIMAL(10, 3) DEFAULT NULL,"
+ "open DECIMAL(10, 3) DEFAULT NULL,"
+ "high DECIMAL(10, 3) DEFAULT NULL,"
+ "low DECIMAL(10, 3) DEFAULT NULL,"
+ "volume BIGINT DEFAULT NULL,"
+ "amount BIGINT DEFAULT NULL,"
+"code INT DEFAULT NULL,"
+"ticktime VARCHAR(100) DEFAULT NULL,"
+"per DECIMAL(10, 3) DEFAULT NULL,"
+"pb DECIMAL(10, 3) DEFAULT NULL,"
+"mktcap DECIMAL(20, 3) DEFAULT NULL,"
+"nmc DECIMAL(20, 3) DEFAULT NULL,"
+"turnoverratio DECIMAL(10, 5) DEFAULT NULL,"
+"createtime TIMESTAMP DEFAULT NULL)";
stmt.executeUpdate(createTableSQL);
System.out.println("Created table: " + tableName);
quotes.setSymbol(jsonData.getString("symbol"));
quotes.setName(jsonData.getString("name"));
quotes.setTrade(jsonData.getBigDecimal("trade"));
quotes.setPricechange(jsonData.getBigDecimal("pricechange"));
quotes.setChangepercent(jsonData.getBigDecimal("changepercent"));
quotes.setBuy(jsonData.getBigDecimal("buy"));
quotes.setSell(jsonData.getBigDecimal("sell"));
quotes.setSettlement(jsonData.getBigDecimal("settlement"));
quotes.setOpen(jsonData.getBigDecimal("open"));
quotes.setHigh(jsonData.getBigDecimal("high"));
quotes.setLow(jsonData.getBigDecimal("low"));
quotes.setVolume(jsonData.getInteger("volume"));
quotes.setAmount(jsonData.getInteger("amount"));
quotes.setCode(jsonData.getInteger("code"));
quotes.setTicktime(jsonData.getString("ticktime"));
Date date = new Date();
quotes.setCreatetime(date);
objects.add(quotes);
stockdataService.add(quotes);
}
}
stockdataService.saveBatch(objects);
// 具体返回示例值,参考返回参数说明、json返回示例
System.out.println("jsonObject: " + jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
return R.success(jsonObject);
}
// 将map型转为请求参数型
public static String urlencode(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* get方式的http请求
*
* @param httpUrl 请求地址
* @param paramStr 请求参数
* @return 返回结果
*/
public static String doGet(String httpUrl, String paramStr) {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
String result = null;// 返回结果字符串
try {
httpUrl += "?" + paramStr;
// 创建远程url连接对象
URL url = new URL(httpUrl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 封装输入流,并指定字符集
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();// 关闭远程连接
}
}
return result;
}
/**
* post方式的http请求
*
* @param httpUrl 请求地址
* @param paramStr 请求参数
* @return 返回结果
*/
public static String doPost(String httpUrl, String paramStr) {
HttpURLConnection connection = null;
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 通过连接对象获取一个输出流
outputStream = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
outputStream.write(paramStr.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
}