欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java通過HTTP接收json詳細(xì)實(shí)例代碼

 更新時(shí)間:2023年11月23日 10:02:59   作者:SAPmatinal  
Java作為一門廣泛使用的編程語言,很多開發(fā)人員會(huì)用它來進(jìn)行http請求,獲取json數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于java通過HTTP接收json的相關(guān)資料,需要的朋友可以參考下

一: json接收類

第一個(gè)接口為直接傳參接收

第二個(gè)接口接收json字符串

可以寫個(gè)HTTP測試類調(diào)用測試,也可以postman測試調(diào)用,實(shí)例方法貼到下面

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字符串轉(zhuǎn)換為JSONObject類型
JSONObject jsonObject = JSONObject.parseObject(newMssage);
//從JSONObject 對象中獲取指定key(即這里的data)對應(yīng)的值
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”,“發(fā)送成功”);
map.put(“msg”,“ok”);
map.put(“code”,“200”);
return map;
}
map.put(“data”,“發(fā)送失敗”);
map.put(“msg”,“ok”);
map.put(“code”,“777”);
return map;
}

//電網(wǎng)
@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","發(fā)送成功");
        map.put("msg","ok");
        map.put("code","200");
        return map;
    }
    map.put("data","發(fā)送失敗");
    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) {

// 創(chuàng)建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();

String resultString = “”;
CloseableHttpResponse response = null;
try {
// 創(chuàng)建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 創(chuàng)建http GET請求
HttpGet httpGet = new HttpGet(uri);
// 執(zhí)行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為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) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = “”;
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建參數(shù)列表
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);
}
// 執(zhí)行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) {
// 創(chuàng)建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = “”;
try {
// 創(chuàng)建Http Post請求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建請求內(nèi)容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 執(zhí)行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 = "服務(wù)器異常";
        }
    } catch (Exception e) {
        System.out.println("請求異常");
        throw new RuntimeException(e);
    }
    System.out.println("result==" + result);
    return result;
}
}

總結(jié) 

到此這篇關(guān)于java通過HTTP接收json的文章就介紹到這了,更多相關(guān)java HTTP接收json內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java groovy如何提升代碼運(yùn)行效率

    Java groovy如何提升代碼運(yùn)行效率

    這篇文章主要介紹了Java groovy如何提升代碼運(yùn)行效率,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • Java中ModelMapper?的高級使用

    Java中ModelMapper?的高級使用

    本文主要介紹了Java中ModelMapper?的高級使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Spring Boot 3.x 全新的熱部署配置方式詳解(IntelliJ IDEA 2023.1)

    Spring Boot 3.x 全新的熱部署配置方式詳解(IntelliJ ID

    這篇文章主要介紹了Spring Boot 3.x 全新的熱部署配置方式(IntelliJ IDEA 2023.1),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • Java 判斷IP地址的合法性實(shí)例詳解

    Java 判斷IP地址的合法性實(shí)例詳解

    這篇文章主要介紹了Java 判斷IP地址的合法性實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • Nacos源碼之注冊中心的實(shí)現(xiàn)詳解

    Nacos源碼之注冊中心的實(shí)現(xiàn)詳解

    這篇文章主要為大家介紹了Nacos源碼之注冊中心的實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-02-02
  • spring boot中的靜態(tài)資源加載處理方式

    spring boot中的靜態(tài)資源加載處理方式

    這篇文章主要介紹了spring boot中的靜態(tài)資源加載處理方式,需要的朋友可以參考下
    2017-04-04
  • Spring WebSocket 404錯(cuò)誤的解決方法

    Spring WebSocket 404錯(cuò)誤的解決方法

    這篇文章主要為大家詳細(xì)介紹了Spring WebSocket 404錯(cuò)誤的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Java中MyBatis的動(dòng)態(tài)語句詳解

    Java中MyBatis的動(dòng)態(tài)語句詳解

    這篇文章主要介紹了Java中MyBatis的動(dòng)態(tài)語句詳解,動(dòng)態(tài) SQL 是 MyBatis 的強(qiáng)大特性之一,通過不同參數(shù)生成不同的 SQL,可以動(dòng)態(tài)地對數(shù)據(jù)持久層進(jìn)行操作,而不需要每個(gè)數(shù)據(jù)訪問操作都要進(jìn)行手動(dòng)地拼接 SQL 語句,需要的朋友可以參考下
    2023-08-08
  • 基于java中byte數(shù)組與int類型的轉(zhuǎn)換(兩種方法)

    基于java中byte數(shù)組與int類型的轉(zhuǎn)換(兩種方法)

    下面小編就為大家?guī)硪黄趈ava中byte數(shù)組與int類型的轉(zhuǎn)換(兩種方法)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-08-08
  • SpringBoot常用注解詳細(xì)整理

    SpringBoot常用注解詳細(xì)整理

    大家好,本篇文章主要講的是SpringBoot常用注解詳細(xì)整理,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12

最新評論