• 《Java知识应用》Java通过Get和Post实现HTTP请求。


    Http请求,是非常常见并且的数据交互方式。

    下面讲解:Get和Post的两个实战案例。

    用于测试的Action(controller)。

    @RequestMapping(value = "getData.json")
    public @ResponseBody
    ServerResponse getData(HttpSession session,@RequestBody People people){
        return new ServerResponse(people);
    }

    案例(post):

    import org.json.JSONObject;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Main {
        private static final String URL= "http://XXX.XXX.XXX.XXX:XXXX/getData.json";
    
        public static void main(String[] args) {
            String url = URL;
            Map map = new HashMap();
            map.put("name","李磊");
            map.put("age","18");
            JSONObject json = new JSONObject(map);
            JSONObject res = PostInterface.postJson(url,json);
            System.out.println(res.toString());
        }
    }
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONObject;
    
    import java.nio.charset.Charset;
    
    /**
     * 请求类
     */
    public class PostInterface {
    
        public static JSONObject postJson(String url, JSONObject json) {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            JSONObject response = null;
            try {
                //编码使用UTF-8,避免中文乱码
                StringEntity s = new StringEntity(json.toString(), Charset.forName("GBK"));
                s.setContentType("application/json");//发送json数据需要设置contentType
                post.setEntity(s);
    
                HttpResponse res = httpclient.execute(post);
                if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                    response = new JSONObject(result);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return response;
        }
    }

    运行结果:

    用于测试的Action(controller)。

    @RequestMapping(value = "getData.json")
    public @ResponseBody
    ServerResponse getData(HttpSession session, String flag){
        String str;
        if(!StringUtils.isBlank(flag)){
            str = "您传的是“"+flag+"”";
        }else{
            str = "您传的是空";
        }
        return new ServerResponse(str);
    }

    案例(get):

    public class Main {
        private static final String URL= "http://XXX.XXX.XXX.XXX:XXXX/getData.json";
    
        public static void main(String[] args) {
            String url = URL;
            String res = PostInterface.doGet(url+"?flag=1","utf-8");
            System.out.println(res.toString());
        }
    }
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    
    /**
     * 请求类
     */
    public class PostInterface {
    
        public static String doGet(String url,String charset){
            if(null == charset){
                charset = "utf-8";
            }
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpGet httpGet = null;
            String result = null;
            try {
                httpGet = new HttpGet(url);
                HttpResponse response = httpclient.execute(httpGet);
                if(response != null){
                    HttpEntity resEntity = response.getEntity();
                    if(resEntity != null){
                        result = EntityUtils.toString(resEntity,charset);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    运行结果:

    如果在执行案例过程遇到问题:可以加群沟通,或者下面留言

    This moment will nap, you will have a dream; But this moment study,you will interpret a dream.
  • 相关阅读:
    pch”预编译头文件来自编译器的其他版本,或者预编译头为 C++ 而在 C 中使用它(或相反) and vs找不到路径
    VC++获得当前系统时间的几种方案
    无法解析的外部符号 __imp____glutInitWithExit@12,该符号在函数 _glutInit_ATEXIT_HACK@8 中被引用
    error C2381: “exit” : 重定义
    vs2019 link glaux.lib 无法解析的外部符号,是缺少一个Lib
    操作系统算法整理+汇总
    vs2019配置glm包
    第二题 既约分数
    死磕Spring之IoC篇
    精尽Spring Boot源码分析
  • 原文地址:https://www.cnblogs.com/jssj/p/11598651.html
Copyright © 2020-2023  润新知