參考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中 '? '后的參數(shù)字符串一致
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;
}