演示项目
This commit is contained in:
3
api/path/to/file
Normal file
3
api/path/to/file
Normal file
@@ -0,0 +1,3 @@
|
||||
user_id,comment,labels
|
||||
wxxwjef,This is a way,[]
|
||||
hahah,No matter,[]
|
||||
@@ -6,8 +6,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.wx.application.gorse4j.GorsePage;
|
||||
import com.wx.application.gorse4j.User;
|
||||
import com.wx.application.gorse4j.*;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -17,8 +16,6 @@ import com.wx.application.base.BaseController;
|
||||
import com.wx.application.base.ResponseData;
|
||||
import com.wx.application.core.service.EntrysService;
|
||||
import com.wx.application.core.service.RiskUserService;
|
||||
import com.wx.application.gorse4j.GorseService;
|
||||
import com.wx.application.gorse4j.Item;
|
||||
import com.wx.application.nebula.graph.query.NebulaModel;
|
||||
import com.wx.application.nebula.graph.query.NebulaNode;
|
||||
import com.wx.application.nebula.graph.service.ImportGraphService;
|
||||
@@ -35,12 +32,6 @@ public class GorseController extends BaseController {
|
||||
@Autowired
|
||||
GorseService gorseService;
|
||||
|
||||
@Autowired
|
||||
RiskUserService riskUserService;
|
||||
|
||||
@Autowired
|
||||
EntrysService entrysService;
|
||||
|
||||
@Autowired
|
||||
NebulaOperateService nebulaOperateService;
|
||||
|
||||
@@ -56,13 +47,7 @@ public class GorseController extends BaseController {
|
||||
*/
|
||||
@PostMapping(value = "/recommend_by_userid")
|
||||
public ResponseData recommendByUserId(@RequestBody GorseQ gQo) throws Exception {
|
||||
List<String> res = gorseService.getRecommend(gQo.getUserId());
|
||||
if (res == null || res.size() == 0) {
|
||||
return success();
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("INS_fid", StringUtils.join(res, ","));
|
||||
return success(entrysService.queryList(mQ));
|
||||
return success(gorseService.getRecommend(gQo.getUserId()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,6 +70,26 @@ public class GorseController extends BaseController {
|
||||
return success();
|
||||
}
|
||||
|
||||
@PostMapping(value = "/delete_user/{userId}")
|
||||
public ResponseData deleteUser(@PathVariable("userId") String userId) throws Exception {
|
||||
return success(gorseService.deleteUser(userId));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/get_item/{itemId}")
|
||||
public ResponseData getItem(@PathVariable("itemId") String itemId) throws Exception {
|
||||
return success(gorseService.getItem(itemId));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/get_user/{userId}")
|
||||
public ResponseData getUser(@PathVariable("userId") String userId) throws Exception {
|
||||
return success(gorseService.getUser(userId));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/delete_item/{itemId}")
|
||||
public ResponseData deleteItem(@PathVariable("itemId") String itemId) throws Exception {
|
||||
return success(gorseService.deleteItem(itemId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 推荐根据知识图谱
|
||||
*
|
||||
@@ -102,13 +107,7 @@ public class GorseController extends BaseController {
|
||||
nodes.get(0).getVid();
|
||||
}
|
||||
|
||||
List<String> res = gorseService.getRecommend(gQo.getUserId());
|
||||
if (res == null || res.size() == 0) {
|
||||
return success();
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("INS_fid", StringUtils.join(res, ","));
|
||||
return success(entrysService.queryList(mQ));
|
||||
return success(gorseService.getRecommend(gQo.getUserId()));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/get_similar_user")
|
||||
@@ -116,6 +115,11 @@ public class GorseController extends BaseController {
|
||||
return success(gorseService.getSimilarUser(gQo.getUserId()));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/get_similar_item")
|
||||
public ResponseData getSimilarItem(@RequestBody GorseQ gQo) throws Exception {
|
||||
return success(gorseService.getSimilarItem(gQo.getItemId(), gQo.getCategory(), gQo.getN()));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/get_recommend_by_user")
|
||||
public ResponseData getRecommendByUser(@RequestBody GorseQ gQo) throws Exception {
|
||||
return success(gorseService.getRecommendByUser(gQo.getUserId(), gQo.getRecommendation(), gQo.getCategory(), gQo.getN()));
|
||||
@@ -126,6 +130,16 @@ public class GorseController extends BaseController {
|
||||
return success(gorseService.listFeedback(userId, type));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/insert_feedback/{type}/{userId}/{itemId}")
|
||||
public ResponseData insertFeedback(@PathVariable("userId") String userId, @PathVariable("type") String type,
|
||||
@PathVariable("itemId") String itemId) throws Exception {
|
||||
List<Feedback> list = new ArrayList<>();
|
||||
Feedback fb = new Feedback();
|
||||
fb.init(userId, itemId, type);
|
||||
list.add(fb);
|
||||
return success(gorseService.insertFeedback(list));
|
||||
}
|
||||
|
||||
@PutMapping(value = "/bulk/{type}")
|
||||
public ResponseData bulkUserOrItem(@RequestParam Map<String, String> data, @RequestParam("file") MultipartFile file, @PathVariable("type") String type) throws Exception {
|
||||
return success(gorseService.bulkUserOrItem(data, file, type));
|
||||
@@ -138,74 +152,22 @@ public class GorseController extends BaseController {
|
||||
|
||||
@GetMapping(value = "/query_users")
|
||||
public ResponseData queryUsers(@RequestParam("cursor") String cursor) throws Exception {
|
||||
GorsePage page = gorseService.getUserPageByCursor(cursor);
|
||||
if (page.getUsers() == null || page.getUsers().size() == 0) {
|
||||
return success(page);
|
||||
}
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (User user : page.getUsers()) {
|
||||
ids.add(user.getUserId());
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("INS_fid", StringUtils.join(ids, ","));
|
||||
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("cursor", page.getCursor());
|
||||
obj.put("users", riskUserService.queryList(mQ));
|
||||
return success(obj);
|
||||
return success(gorseService.getUserPageByCursor(cursor));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/query_user/{id}")
|
||||
public ResponseData queryUser(@PathVariable("id") String id) {
|
||||
User user = null;
|
||||
try {
|
||||
user = gorseService.getUserById(id);
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
if (user == null) {
|
||||
return success();
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("EQS_fid", user.getUserId());
|
||||
return success(riskUserService.queryUnique(mQ));
|
||||
public ResponseData queryUser(@PathVariable("id") String id) throws Exception {
|
||||
return success(gorseService.getUserById(id));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/query_items")
|
||||
public ResponseData queryItems(@RequestParam("cursor") String cursor) throws Exception {
|
||||
GorsePage page = gorseService.getItemPageByCursor(cursor);
|
||||
if (page.getItems() == null || page.getItems().size() == 0) {
|
||||
return success(page);
|
||||
}
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (Item item : page.getItems()) {
|
||||
ids.add(item.getItemId());
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("INS_fid", StringUtils.join(ids, ","));
|
||||
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("cursor", page.getCursor());
|
||||
obj.put("items", entrysService.queryList(mQ));
|
||||
return success(obj);
|
||||
return success(gorseService.getItemPageByCursor(cursor));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/query_item/{id}")
|
||||
public ResponseData queryItem(@PathVariable("id") String id) {
|
||||
Item item = null;
|
||||
try {
|
||||
item = gorseService.getItemById(id);
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
if (item == null) {
|
||||
return success();
|
||||
}
|
||||
Map mQ = new HashMap<>();
|
||||
mQ.put("EQS_fid", item.getItemId());
|
||||
return success(entrysService.queryUnique(mQ));
|
||||
public ResponseData queryItem(@PathVariable("id") String id) throws Exception {
|
||||
return success(gorseService.getItemById(id));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -10,8 +10,15 @@ import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.api.R;
|
||||
import com.wx.application.core.mapper.RiskUserMapper;
|
||||
import com.wx.application.gorse4j.GorseService;
|
||||
import com.wx.application.gorse4j.User;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
//import org.redisson.api.RedissonClient;
|
||||
import org.checkerframework.checker.units.qual.A;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
@@ -40,11 +47,14 @@ import lombok.extern.slf4j.Slf4j;
|
||||
@RestController("loginController")
|
||||
public class LoginController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
RiskUserService riskUserService;
|
||||
|
||||
/*@Autowired
|
||||
RedissonClient redissonClient;*/
|
||||
@Autowired
|
||||
RiskUserService riskUserService;
|
||||
|
||||
@Autowired
|
||||
RiskUserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
GorseService gorseService;
|
||||
|
||||
@Autowired
|
||||
private Kaptcha kaptcha;
|
||||
@@ -72,68 +82,75 @@ public class LoginController extends BaseController {
|
||||
kaptcha.render();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*/
|
||||
@PostMapping(value = "/user")
|
||||
public ResponseData login(@RequestBody RiskUserQ loginQo) throws Exception {
|
||||
|
||||
// if(StringUtils.isBlank(loginQo.getCode())) {
|
||||
// Map<String,String> data = new HashMap<>();
|
||||
// data.put("msg", "验证码不能为空");
|
||||
// return error(ErrorCodeEnum.USER_NOT_EXIST,data);
|
||||
// }
|
||||
//
|
||||
// try {
|
||||
// kaptcha.validate(loginQo.getCode());
|
||||
// } catch (Exception e) {
|
||||
// Map<String,String> data = new HashMap<>();
|
||||
// data.put("msg", "验证码错误");
|
||||
// return error(ErrorCodeEnum.USER_NOT_EXIST,data);
|
||||
// }
|
||||
|
||||
/*if(StringUtils.isBlank(loginQo.getCode())) {
|
||||
Map<String,String> data = new HashMap<>();
|
||||
data.put("msg", "验证码不能为空");
|
||||
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
|
||||
}
|
||||
|
||||
try {
|
||||
kaptcha.validate(loginQo.getCode());
|
||||
} catch (Exception e) {
|
||||
Map<String,String> data = new HashMap<>();
|
||||
data.put("msg", "验证码错误");
|
||||
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 将密码改成md5加密查询
|
||||
*/
|
||||
Map<String,Object> mQ = new HashMap<>();
|
||||
mQ.put("EQS_username", loginQo.getUsername());
|
||||
mQ.put("EQS_password", MD5Util.MD5(loginQo.getPassword()));
|
||||
mQ.put("EQS_type", loginQo.getType());
|
||||
|
||||
RiskUser riskUser = riskUserService.queryUnique(mQ);
|
||||
|
||||
if(riskUser != null) {
|
||||
String token = JwtUtils.generateJwtToken(riskUser.getId(), CONSTANT.LOGIN_TYPE_ADMIN, riskUser);
|
||||
|
||||
RiskUser _riskUser = new RiskUser();
|
||||
_riskUser.setRealname(riskUser.getRealname());
|
||||
_riskUser.setUsername(riskUser.getUsername());
|
||||
|
||||
return success(ImmutableMap.<String, Object>builder()
|
||||
.put("Authorization",token)
|
||||
.put("user", _riskUser)
|
||||
.build());
|
||||
}
|
||||
Map<String,String> data = new HashMap<>();
|
||||
data.put("msg", "用户名密码错误");
|
||||
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
|
||||
/**
|
||||
* 登录
|
||||
*/
|
||||
@PostMapping(value = "/user")
|
||||
public ResponseData login(@RequestBody RiskUserQ loginQo) throws Exception {
|
||||
|
||||
/**
|
||||
* 将密码改成md5加密查询
|
||||
*/
|
||||
Map<String, Object> mQ = new HashMap<>();
|
||||
mQ.put("EQS_username", loginQo.getUsername());
|
||||
mQ.put("EQS_password", MD5Util.MD5(loginQo.getPassword()));
|
||||
mQ.put("EQS_type", loginQo.getType());
|
||||
|
||||
RiskUser riskUser = riskUserService.queryUnique(mQ);
|
||||
|
||||
if (riskUser != null) {
|
||||
String token = JwtUtils.generateJwtToken(riskUser.getId(), CONSTANT.LOGIN_TYPE_ADMIN, riskUser);
|
||||
|
||||
RiskUser _riskUser = new RiskUser();
|
||||
_riskUser.setRealname(riskUser.getUsername());
|
||||
_riskUser.setUsername(riskUser.getUsername());
|
||||
|
||||
return success(ImmutableMap.<String, Object>builder()
|
||||
.put("Authorization", token)
|
||||
.put("user", _riskUser)
|
||||
.build());
|
||||
}
|
||||
Map<String, String> data = new HashMap<>();
|
||||
data.put("msg", "用户名密码错误");
|
||||
return error(ErrorCodeEnum.USER_NOT_EXIST, data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 注册
|
||||
*/
|
||||
@PostMapping(value = "/register")
|
||||
public ResponseData register(@RequestBody RiskUserQ registerQ) throws Exception {
|
||||
|
||||
|
||||
Map<String, String> data = new HashMap<>();
|
||||
if (StringUtils.isEmpty(registerQ.getUsername()) || StringUtils.isEmpty(registerQ.getPassword())) {
|
||||
data.put("msg", "用户名密码不能为空");
|
||||
return error(ErrorCodeEnum.PARAM_ERROR, data);
|
||||
}
|
||||
|
||||
int blankUserCount = userMapper.selectCount(new QueryWrapper<RiskUser>().lambda().eq(RiskUser::getUsername, registerQ.getUsername()));
|
||||
if (blankUserCount > 0) {
|
||||
data.put("msg", "用户名已存在");
|
||||
return error(ErrorCodeEnum.MOBILE_USED, data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将密码改成md5加密
|
||||
*/
|
||||
RiskUser nowUser = new RiskUser();
|
||||
nowUser.setUsername(registerQ.getUsername());
|
||||
nowUser.setPassword(MD5Util.MD5(registerQ.getPassword()));
|
||||
nowUser.setType(registerQ.getType());
|
||||
|
||||
userMapper.insert(nowUser);
|
||||
// User user = new User(registerQ.getUsername(), null);
|
||||
// gorseService.insertUser(user);
|
||||
return success();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密用户敏感数据获取用户信息
|
||||
*
|
||||
|
||||
@@ -17,6 +17,12 @@ public class Feedback {
|
||||
public Feedback() {
|
||||
}
|
||||
|
||||
public void init(String userId, String itemId, String feedbackType) {
|
||||
this.itemId = itemId;
|
||||
this.userId = userId;
|
||||
this.feedbackType = feedbackType;
|
||||
}
|
||||
|
||||
public Feedback(String feedbackType, String userId, String itemId, String timestamp, Item item) {
|
||||
this.feedbackType = feedbackType;
|
||||
this.userId = userId;
|
||||
|
||||
@@ -4,6 +4,8 @@ import com.alibaba.fastjson.JSONObject;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
|
||||
import com.wx.application.util.CSVUtils;
|
||||
import com.wx.application.util.HttpUtils;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
@@ -13,12 +15,11 @@ import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -65,8 +66,9 @@ public class GorseService {
|
||||
return this.request("DELETE", this.endpoint + "/api/item/" + itemId, null, RowAffected.class);
|
||||
}
|
||||
|
||||
public RowAffected insertFeedback(List<Feedback> feedbacks) throws IOException {
|
||||
return this.request("POST", this.endpoint + "/api/feedback", feedbacks, RowAffected.class);
|
||||
public Object insertFeedback(List<Feedback> feedbacks) throws IOException {
|
||||
return HttpUtils.doPost(this.endpoint + "/api/feedback", JSONObject.toJSONString(feedbacks));
|
||||
// return this.request("POST", this.endpoint + "/api/feedback", feedbacks, RowAffected.class);
|
||||
}
|
||||
|
||||
public List<Feedback> listFeedback(String userId, String feedbackType) throws IOException {
|
||||
@@ -152,6 +154,7 @@ public class GorseService {
|
||||
*/
|
||||
public JSONObject bulkUserOrItem(Map<String, String> data, MultipartFile multipartFile, String type) throws IOException {
|
||||
File file = new File("path/to/file");
|
||||
|
||||
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
|
||||
|
||||
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
@@ -159,6 +162,14 @@ public class GorseService {
|
||||
builder.addTextBody(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
// 导入附加的属性数据到mysql
|
||||
if ("users".equals(type)) {
|
||||
List<List<String>> rows = CSVUtils.parseCSV(file, data.get("sep"));
|
||||
|
||||
} else if ("items".equals(type)) {
|
||||
List<List<String>> rows = CSVUtils.parseCSV(file, data.get("sep"));
|
||||
}
|
||||
|
||||
builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, multipartFile.getOriginalFilename());
|
||||
return this.sendPostFormData(this.endpoint + "/api/bulk/" + type, builder);
|
||||
}
|
||||
@@ -200,12 +211,15 @@ public class GorseService {
|
||||
if (request != null) {
|
||||
connection.setDoOutput(true);
|
||||
String requestBody = mapper.writeValueAsString(request);
|
||||
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
|
||||
OutputStream outputStream = connection.getOutputStream();
|
||||
outputStream.write(requestBody.getBytes());
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
}
|
||||
// Get Response
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
return mapper.readValue(inputStream, responseClass);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
52
api/src/main/java/com/wx/application/util/CSVUtils.java
Normal file
52
api/src/main/java/com/wx/application/util/CSVUtils.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.wx.application.util;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class CSVUtils {
|
||||
|
||||
/**
|
||||
* @param file
|
||||
* @param sep 属性分隔符
|
||||
* @return
|
||||
* @throws FileNotFoundException
|
||||
*/
|
||||
public static List<List<String>> parseCSV(File file, String sep) throws FileNotFoundException {
|
||||
List<List<String>> rows = new ArrayList<>();
|
||||
|
||||
if (file == null) {
|
||||
return rows;
|
||||
}
|
||||
|
||||
if (StringUtils.isEmpty(sep)) {
|
||||
sep = ",";
|
||||
}
|
||||
|
||||
try {
|
||||
Scanner scanner = new Scanner(file);
|
||||
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine();
|
||||
String[] values = line.split(sep);
|
||||
List<String> row = new ArrayList<>();
|
||||
|
||||
for (String value : values) {
|
||||
row.add(value);
|
||||
}
|
||||
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
191
api/src/main/java/com/wx/application/util/HttpUtils.java
Normal file
191
api/src/main/java/com/wx/application/util/HttpUtils.java
Normal file
@@ -0,0 +1,191 @@
|
||||
package com.wx.application.util;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpUtils {
|
||||
|
||||
|
||||
private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
|
||||
private static RequestConfig requestConfig;
|
||||
|
||||
/**
|
||||
* 情况方法直接放这里就行
|
||||
*/
|
||||
|
||||
|
||||
static {
|
||||
connMgr.setMaxTotal(100);
|
||||
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
|
||||
RequestConfig.Builder configBuilder = RequestConfig.custom();
|
||||
configBuilder.setConnectTimeout(60000);
|
||||
configBuilder.setSocketTimeout(70000);
|
||||
configBuilder.setConnectionRequestTimeout(30000);
|
||||
requestConfig = configBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定URL发送GET方法的请求
|
||||
*
|
||||
* @param url 发送请求的URL
|
||||
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
|
||||
* @return URL 所代表远程资源的响应结果
|
||||
*/
|
||||
public Object sendGet(String url, String param) {
|
||||
String result = "";
|
||||
BufferedReader in = null;
|
||||
try {
|
||||
String urlNameString = url + "?" + param;
|
||||
URL realUrl = new URL(urlNameString);
|
||||
// 打开和URL之间的连接
|
||||
URLConnection connection = realUrl.openConnection();
|
||||
// 设置通用的请求属性
|
||||
connection.setRequestProperty("accept", "*/*");
|
||||
connection.setRequestProperty("connection", "Keep-Alive");
|
||||
connection.setRequestProperty("user-agent",
|
||||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
// 建立实际的连接
|
||||
connection.connect();
|
||||
// 获取所有响应头字段
|
||||
Map<String, List<String>> map = connection.getHeaderFields();
|
||||
// 遍历所有的响应头字段
|
||||
for (String key : map.keySet()) {
|
||||
System.out.println(key + "--->" + map.get(key));
|
||||
}
|
||||
// 定义 BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader(new InputStreamReader(
|
||||
connection.getInputStream()));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result += line;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("发送GET请求出现异常!" + e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
// 使用finally块来关闭输入流
|
||||
finally {
|
||||
try {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
} catch (Exception e2) {
|
||||
e2.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定 URL 发送POST方法的请求
|
||||
*
|
||||
* @param url 发送请求的 URL
|
||||
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
|
||||
* @return 所代表远程资源的响应结果
|
||||
*/
|
||||
public static Object sendPost(String url, String param) {
|
||||
PrintWriter out = null;
|
||||
BufferedReader in = null;
|
||||
String result = "";
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
URLConnection conn = realUrl.openConnection();
|
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("accept", "*/*");
|
||||
conn.setRequestProperty("connection", "Keep-Alive");
|
||||
conn.setRequestProperty("user-agent",
|
||||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
// 获取URLConnection对象对应的输出流
|
||||
out = new PrintWriter(conn.getOutputStream());
|
||||
// 发送请求参数
|
||||
out.print(param);
|
||||
// flush输出流的缓冲
|
||||
out.flush();
|
||||
// 定义BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream()));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result += line;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("发送 POST 请求出现异常!" + e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
//使用finally块来关闭输出流、输入流
|
||||
finally {
|
||||
try {
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* post,以 application/json 形式
|
||||
* @param apiUrl
|
||||
* @param json
|
||||
* @return
|
||||
*/
|
||||
public static String doPost(String apiUrl, String json) {
|
||||
long start = System.currentTimeMillis();
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
String httpStr = null;
|
||||
HttpPost httpPost = new HttpPost(apiUrl);
|
||||
CloseableHttpResponse response = null;
|
||||
int statusCode = -999;
|
||||
try {
|
||||
httpPost.setConfig(requestConfig);
|
||||
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
|
||||
stringEntity.setContentEncoding("UTF-8");
|
||||
stringEntity.setContentType("application/json");
|
||||
httpPost.setEntity(stringEntity);
|
||||
response = httpClient.execute(httpPost);
|
||||
HttpEntity entity = response.getEntity();
|
||||
statusCode = response.getStatusLine().getStatusCode();
|
||||
httpStr = EntityUtils.toString(entity, "UTF-8");
|
||||
} catch (Exception var20) {
|
||||
var20.printStackTrace();
|
||||
} finally {
|
||||
if (response != null) {
|
||||
try {
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} catch (IOException var19) {
|
||||
var19.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return httpStr;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user