参考1:https://blog.csdn.net/w348399060/article/details/62424502
下面给出两个方法:
/*分词方法1——获取分词列表*/
public static List SegWord_method(String title) throws IOException {
List wordList = new ArrayList();
StringBuffer response = new StringBuffer();
HttpURLConnection connection = null;
try {
String url = "http://c*******?";
// 请求url
URL postUrl = new URL(url);
// 打开连接
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST"); // 默认是 GET方式
connection.setUseCaches(false); // Post 请求不能使用缓存
connection.setInstanceFollowRedirects(true); //设置本次连接是否自动重定向
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Connection","Keep-Alive");//设置与服务器保持连接
connection.setRequestProperty("Accept-Language", "zh-CN,zh;0.9");
// 连接
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
// 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
String content = "i=" + URLEncoder.encode(title, "utf-8");
out.writeBytes(content);
//流用完记得关
out.flush();
out.close();
//获取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
response.append(line);
// System.out.println("debug--line:" + line);
}
reader.close();
connection.disconnect();
//将获取结果转化为列表
JSONObject result = JSON.parseObject(response.toString());
com.jd.fastjson.JSONArray data = result.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject b = data.getJSONObject(i);
String word = b.getString("word");
// System.out.println("word:" + word);
wordList.add(word);
}
}catch (Exception e){
logger.error("error");
e.printStackTrace();
}
return wordList;
}
// 分词方法2——获取分词列表
public static List SegWord_method2(String title) {
String url = "http://cwss**************?i=" + title;
List wordList = new ArrayList();
StringBuilder response = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//将获取json字符串response转化为需要的列表
JSONObject result = JSON.parseObject(response.toString());
com.jd.fastjson.JSONArray data = result.getJSONArray("data");
for (int i = 0; i < data.size(); i++) {
JSONObject b = data.getJSONObject(i);
String word = b.getString("word"); //每个词
wordList.add(word);
}
} catch (IOException e) {
logger.error("error");
e.printStackTrace();
}
return wordList;
}
网友评论