java调用http接口并返回json对象

时间:2021-08-25
本文章向大家介绍java调用http接口并返回json对象,主要包括java调用http接口并返回json对象使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

public class Test {

    //调用http接口
    @RequestMapping(value="testInterfaces.htm", method={RequestMethod.GET, RequestMethod.POST})
    public void testInterfaces(HttpServletRequest request) throws Exception{
        //传入中文参数并设置编码格式
        String param = "{\"url\":\"中文\"}";
        param = URLEncoder.encode(param, "UTF-8");
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
               URL realUrl = new URL("http://localhost/test.htm");
               // 打开和URL之间的连接
               URLConnection conn = realUrl.openConnection();
               // 发送POST请求必须设置如下两行
               conn.setDoOutput(true);
               conn.setDoInput(true);
               // 获取URLConnection对象对应的输出流
               out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
               // 发送请求参数
               out.print(param);
               // flush输出流的缓冲
               out.flush();
               // 定义BufferedReader输入流来读取URL的响应
               in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
               String line;
               while ((line = in.readLine()) != null) {
                   result += line;
               }
               //解析json对象
               JSONObject jsStr = JSONObject.fromObject(result);
               System.out.println(jsStr.get("firstName"));
            } catch (Exception e) {
               e.printStackTrace();
            }
    }

    //所调用的接口
    @RequestMapping(value = "test.htm", method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public JSONObject test(HttpServletRequest request)throws Exception {
        JSONObject jsonObj = new JSONObject();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("firstName", "jack");
        jsonObj.putAll(map);
        return jsonObj;
    }

}

原文地址:https://www.cnblogs.com/361ky/p/15183865.html