最近工作中分别做了对接别人的接口以及提供接口的工作,在这里做一下总结。
对接别人的接口
主要记录请求http的工具类以及将bean转换为json的工具类
1.请求http工具类,需要引入httpclient-4.5.1.jar以及httpcore-4.4.11.jar
public class HttpUtil {
/**
* get请求
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = (HttpResponse) client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* post请求(用于key-value格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params){
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
//设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
//System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
//logger.error("请求返回:"+state+"("+url+")");
System.out.println("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
2.bean转换为json工具类,需要引入jackson-core-asl-1.9.12.jar以及jackson-mapper-asl-1.9.12.jar
@JsonProperty("QaLists")
List<GuoBanImportModel> qaLists;
转换为json的时候JsonProperty注解可以设置字段
public class JsonUtil {
private static Logger log = LoggerFactory.getLogger(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper();
static{
//对象的所有字段全部列入
objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
//取消默认转换timestamps形式
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
//忽略空Bean转json的错误
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
//所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
public static <T> String obj2String(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}
//格式化
public static <T> String obj2StringPretty(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
}
public static <T> T string2Obj(String str,Class<T> clazz){
if(StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
//处理场景:复杂对象包括Map,List,Set
public static <T> T string2Obj(String str, TypeReference<T> typeReference){
if(StringUtils.isEmpty(str) || typeReference == null){
return null;
}
try {
return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
//处理场景:可变长参数比较灵活,比如:List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);
public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return objectMapper.readValue(str,javaType);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
}
提供接口
采用servlet的形式
public class InterfacesServer extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger("InterfacesServer");
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
String methodName = request.getRequestURI().split("/")[3];
LOGGER.info("调用接口名:"+methodName);
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try {
br = request.getReader();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String receiveData = sb.toString();//请求传过来的json字符串
if (StringUtils.isNotBlank(sb.toString())) {
System.out.println("接收的参数为 :" + sb.toString());
LOGGER.info("接收的参数为 :" + sb.toString());
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
String returnData = "";
if ("searchNewKnowledge".equals(methodName)){
ChangChunAddModel model = JSONObject.parseObject(receiveData,ChangChunAddModel.class);
ServerResponse<List<ChangChunAddModel>> result = searchNewKnowledge(model,request.getRemoteAddr());
returnData = JSON.toJSONString(result);
}else if ("searchKnowledge".equals(methodName)){
KmSearchWSModel model = JSONObject.parseObject(receiveData,KmSearchWSModel.class);
//ServerResponse<ArrayList<KmSearchWSReturnModel>> result = searchKnowledge(model);
//returnData = JSON.toJSONString(result);
}else if ("addKnowledge".equals(methodName)){
EpistemeModel model = JSONObject.parseObject(receiveData,EpistemeModel.class);
ServerResponse<T> result = addKnowledge(model, request.getRemoteAddr());
returnData = JSON.toJSONString(result);
}
returnData = URLEncoder.encode(returnData,"UTF-8");
writer.write(returnData);
LOGGER.info("返回的参数为:"+returnData);
System.out.println("---http call success---");
}
开发中遇到的一些问题:
- “HTTP 405”错误——“Method Not Allowed”
从字面上的意思理解,很显然是提交方法的类型错误,要么是以GET方式向POST接口提交数据,要么是POST方式项GET接口提交数据,但反反复复检查了后端接口与提交方式,都是POST,完全没有问题。- 获取HttpServletRequest请求Body中的内容
https://blog.csdn.net/pengjunlee/article/details/79416687- servlet中获取spring context中的bean
//www.greatytc.com/p/4145f507f3e7- 使用http请求,中文乱码问题--解决方法(都是???????)
https://blog.csdn.net/jie_liang/article/details/77534780- java将clob转换为string(Clob sc = (Clob)object;ClobToString(sc);)
public String ClobToString(Clob sc) throws SQLException, IOException {
String reString = "";
Reader is = sc.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
sb.append(s);
s = br.readLine();
}
reString = sb.toString();
return reString;
}