廖井涛
2025-11-28 67f0be5a1d634ba3274fa9366ceacc3580f056b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.northglass.web.home;
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:8080/gmms2/cutmanage/checktask");
               // 打开和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;
    }
 
}