zoukankan      html  css  js  c++  java
  • 《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.
  • 相关阅读:
    转载--重写、覆盖、重载、多态几个概念的区别分析
    笔试题--奇虎360-2013
    转载---数据挖掘十大经典算法
    Nginx的启动、停止与重启
    程序员的十种级别,看看你属于哪一种?
    C标签的用法
    eclipse修改代码后都需要clean的解决办法
    创建一个jFinal项目
    java redirect用法
    java获取访问者真实的IP地址
  • 原文地址:https://www.cnblogs.com/jssj/p/11598651.html
Copyright © 2011-2022 走看看