java后台通过HTTP接收json并入库

注:最近项目到了尾声,需要同步友商数据,网上看了好多接收json的代码,都是用的io流方式,搞不懂如何入库,自己写了写改了改,.


一: json接收类,
第一个接口为直接传参接收
第二个接口接收json字符串
可以写个HTTP测试类调用测试,也可以postman测试调用,实例方法贴到下面

package com.gt.information.controller;

import com.alibaba.fastjson.JSONObject;
import com.gt.information.dao.DataDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*

  • @date 2020/4/20
    */
    @Controller
    @RequestMapping("/DataController")
    public class DataController {

    @Autowired
    private DataDao DataDao;

    @RequestMapping(value = “apply”, method = RequestMethod.POST, produces = “application/json;charset=UTF-8”)
    @ResponseBody

    public Map<String, String> apply(@RequestBody String newMssage) {
    //将获取的json字符串转换为JSONObject类型
    JSONObject jsonObject = JSONObject.parseObject(newMssage);
    //从JSONObject 对象中获取指定key(即这里的data)对应的值
    String getDataJSBH = jsonObject.getString(“JSBH”);
    String getDataIP = jsonObject.getString(“IP”);
    String getDataDY = jsonObject.getString(“DY”);
    String getDataDL = jsonObject.getString(“DL”);
    String getDataDJZT = jsonObject.getString(“DJZT”);
    List list = new ArrayList();
    Map<String,Object> json = new HashMap<String, Object>();
    json.put(“JSBH”,getDataJSBH);
    json.put(“IP”,getDataIP);
    json.put(“DY”,getDataDY);
    json.put(“DL”,getDataDL);
    json.put(“DJZT”,getDataDJZT);
    list.add(json);
    for (Map user : list) {
    System.out.println(user.toString());
    }
    Map<String,String> map = new HashMap<String, String>();
    int reNum = DataDao.insertDWJL(getDataJSBH,getDataIP,getDataDY,getDataDL,getDataDJZT);
    if(reNum == 1){
    map.put(“data”,“发送成功”);
    map.put(“msg”,“ok”);
    map.put(“code”,“200”);
    return map;
    }
    map.put(“data”,“发送失败”);
    map.put(“msg”,“ok”);
    map.put(“code”,“777”);
    return map;
    }

//电网
@RequestMapping("/dw")
@ResponseBody
public Map<String,Object> dd_ddjlxx(HttpServletRequest request){
String getJSBH = request.getParameter(“JSBH”);
String getIP = request.getParameter(“IP”);
String getDY = request.getParameter(“DY”);
String getDL = request.getParameter(“DL”);
String getDJZT = request.getParameter(“DJZT”);
List list = new ArrayList();
Map<String,Object> json = new HashMap<String, Object>();
json.put(“JSBH”,getJSBH);
json.put(“IP”,getIP);
json.put(“DY”,getDY);
json.put(“DL”,getDL);
json.put(“DJZT”,getDJZT);
list.add(json);
for (Map user : list) {
System.out.println(user.toString());
}
Map<String,Object> map = new HashMap<String, Object>();
int reNum = DataDao.insertDWJL(getJSBH,getIP,getDY,getDL,getDJZT);

    if(reNum == 1){
        map.put("data","发送成功");
        map.put("msg","ok");
        map.put("code","200");
        return map;
    }
    map.put("data","发送失败");
    map.put("msg","ok");
    map.put("code","777");
    return map;
} 

}

二:HTTP工具类
package com.gt.common.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**

  • @author xl

  • @date 2020/4/1-17:04
    */
    public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) {

    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String resultString = “”;
    CloseableHttpResponse response = null;
    try {
    // 创建uri
    URIBuilder builder = new URIBuilder(url);
    if (param != null) {
    for (String key : param.keySet()) {
    builder.addParameter(key, param.get(key));
    }
    }
    URI uri = builder.build();
    // 创建http GET请求
    HttpGet httpGet = new HttpGet(uri);
    // 执行请求
    response = httpclient.execute(httpGet);
    // 判断返回状态是否为200
    if (response.getStatusLine().getStatusCode() == 200) {
    resultString = EntityUtils.toString(response.getEntity(), “UTF-8”);
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (response != null) {
    response.close();
    }
    httpclient.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return resultString;
    }

    public static String doGet(String url) {
    return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = “”;
    try {
    // 创建Http Post请求
    HttpPost httpPost = new HttpPost(url);
    // 创建参数列表
    if (param != null) {
    List paramList = new ArrayList<>();
    for (String key : param.keySet()) {
    paramList.add(new BasicNameValuePair(key, param.get(key)));
    }
    // 模拟表单
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
    httpPost.setEntity(entity);
    }
    // 执行http请求
    response = httpClient.execute(httpPost);
    resultString = EntityUtils.toString(response.getEntity(), “utf-8”);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    response.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

     return resultString;
    

    }

    public static String doPost(String url) {
    return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = “”;
    try {
    // 创建Http Post请求
    HttpPost httpPost = new HttpPost(url);
    // 创建请求内容
    StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
    httpPost.setEntity(entity);
    // 执行http请求
    response = httpClient.execute(httpPost);
    resultString = EntityUtils.toString(response.getEntity(), “utf-8”);
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    response.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

     return resultString;
    

    }
    }
    三:Test测试类
    package com.gt.jszd.analysis.controller;

/**

  • @author xl
  • @date 2020/4/2-11:36
    */

import com.gt.common.util.HttpClientUtil;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestOne {
public static void main(String[] args) {
//JSONObject jsobj1 = new JSONObject();
JSONObject jsobj2 = new JSONObject();
Map<String, String> jsobj1 = new HashMap<String, String>();
/* map.put(“deviceID”, “112”);
map.put(“channel”, “channel”);
map.put(“state”, “0”);
map.put(“item”, “132564”);
map.put(“requestCommand”, “control”);
map.put(“FWQQ_NR”, “123”);*/
jsobj1.put(“JSBH”, “330200111”);
jsobj1.put(“DL”, “0.8A”);
jsobj1.put(“DY”, “2.5V”);
jsobj1.put(“DJZT”, “正常”);
jsobj1.put(“IP”, “192.168.2.135”);
/List list = new ArrayList();
list.add(jsobj1);/
jsobj2.put(“JSBH”, “330200222”);

    jsobj2.put("DL", "0.3A");
    jsobj2.put("DY", "2.2V");
    jsobj2.put("DJZT", "异常");
    jsobj2.put("IP", "192.168.1.135");
    //list.add(jsobj1);
    String url="http://192.168.1.135:8085/DataController/apply";
   // String url="http://192.168.1.135:8085/DataController/Test";
    //post(jsobj2, "http://192.168.1.135:8085/TestConttroller/apply");
    post(jsobj2, url);
    //HttpClientUtil.doPost(url, jsobj1);
    //HttpClientUtil.doPostJson(url, jsobj1.toString());
}


public static String post(JSONObject json, String path) {
    String result = "";
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);
        post.setHeader("Content-Type", "appliction/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        //StringEntity s = new StringEntity(json.toString(), "utf-8");
        StringEntity s = new StringEntity(json.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
        post.setEntity(s);
        HttpResponse httpResponse = client.execute(post);
        InputStream in = httpResponse.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
        StringBuilder strber = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            strber.append(line + "\n");

        }
        in.close();
        result = strber.toString();
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            result = "服务器异常";
        }
    } catch (Exception e) {
        System.out.println("请求异常");
        throw new RuntimeException(e);
    }
    System.out.println("result==" + result);
    return result;
}

}

四:postman调用实例
postman接口一的调用
poatman接口的调用

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值