java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java HTTP接收json

java通过HTTP接收json详细实例代码

作者:SAPmatinal

Java作为一门广泛使用的编程语言,很多开发人员会用它来进行http请求,获取json数据,这篇文章主要给大家介绍了关于java通过HTTP接收json的相关资料,需要的朋友可以参考下

一: 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;

/*

*/
@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;

/**

*/
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;

/**
*/
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;
}
}

总结 

到此这篇关于java通过HTTP接收json的文章就介绍到这了,更多相关java HTTP接收json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文