最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java通過HTTP接收json詳細實例代碼

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

一: json接收類

第一個接口為直接傳參接收

第二個接口接收json字符串

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

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)對應的值
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 = "服務器異常";
        }
    } catch (Exception e) {
        System.out.println("請求異常");
        throw new RuntimeException(e);
    }
    System.out.println("result==" + result);
    return result;
}
}

總結(jié) 

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

相關文章

  • Java 實現(xiàn)滑動時間窗口限流算法的代碼

    Java 實現(xiàn)滑動時間窗口限流算法的代碼

    這篇文章主要介紹了Java 實現(xiàn)滑動時間窗口限流算法的代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Jrebel License Server 激活 IDEA-Jrebel-在線-離線-均適用(推薦)

    Jrebel License Server 激活 IDEA-Jrebel-在線-

    這篇文章主要介紹了Jrebel License Server 激活 IDEA-Jrebel-在線-離線-均適用,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • springboot + swagger 實例代碼

    springboot + swagger 實例代碼

    本篇文章主要介紹了springboot + swagger 實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • Spring Data JPA自動生成表時列順序混亂的最新解決辦法

    Spring Data JPA自動生成表時列順序混亂的最新解決辦法

    文章主要介紹了Spring Boot 3.3.5版本中SpringDataJPA自動生成表時列順序混亂的問題,以及如何通過替換Hibernate實現(xiàn)來解決這個問題,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • java獲取當日、本周、本月、本年的實現(xiàn)方式

    java獲取當日、本周、本月、本年的實現(xiàn)方式

    文章主要討論了在Java中處理日期和時間時使用`LocalDateTime`和`Calendar`類的不同方法,并提到了在使用`LocalDateTime`時需要手動進行格式轉(zhuǎn)換
    2026-02-02
  • log4j升級log4j2遇到的問題及解決方式

    log4j升級log4j2遇到的問題及解決方式

    這篇文章主要介紹了log4j升級log4j2遇到的問題及解決方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 最新Java JDK安裝配置的圖文教程

    最新Java JDK安裝配置的圖文教程

    隨著技術的不斷發(fā)展和更新,Java作為世界上最為流行的編程語言之一,其開發(fā)工具包(JDK)也在持續(xù)更新中,本文旨在為您提供最新版JDK的詳細安裝步驟,通過圖文結(jié)合的方式,幫助您輕松完成Java開發(fā)環(huán)境的搭建,需要的朋友可以參考下
    2025-07-07
  • 關于Spring?Ioc和DI注解的問題

    關于Spring?Ioc和DI注解的問題

    這篇文章主要介紹了Spring?Ioc和DI注解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • 如何剔除eureka無效和down狀態(tài)的問題

    如何剔除eureka無效和down狀態(tài)的問題

    這篇文章主要介紹了如何剔除eureka無效和down狀態(tài)的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • java虛擬機JVM類加載機制原理(面試必問)

    java虛擬機JVM類加載機制原理(面試必問)

    這篇文章主要介紹了面試當中必會問到的java虛擬機JVM類加載機制,非常的詳細,有需要的朋友可以借鑒參考下,歡迎多多交流討論
    2021-08-08

最新評論

贵阳市| 崇仁县| 文化| 山东| 建德市| 亚东县| 乌鲁木齐县| 定日县| 舒城县| 长葛市| 康定县| 改则县| 微山县| 夏邑县| 崇州市| 邛崃市| 苏尼特左旗| 龙里县| 云浮市| 平果县| 石泉县| 临沧市| 民乐县| 万全县| 若羌县| 乌兰县| 克拉玛依市| 韶关市| 应城市| 宁阳县| 炉霍县| 同心县| 呼伦贝尔市| 开原市| 巧家县| 武平县| 湾仔区| 沭阳县| 同心县| 杭锦旗| 平安县|