一个简单的java网络通信例子

先建立2个项目,分别是请求端和响应端,端口改成不一样的就行,比如请求端是8080,响应端是8081

废话不多说,直接上代码

请求端的Controller层

@GetMapping("/request")
    public String hi() {
        HttpClient httpClient = HttpClients.createDefault();
        String url="http://127.0.0.1:8081/response";
        String result=null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type", "application/json;charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("request", "hi, i am request!");    
        httpPost.setEntity(new StringEntity(jsonObject.toJSONString(), "UTF-8"));

        try {
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            } else {
                result = String.valueOf(response.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

响应端的Controller层

@PostMapping("/response")
    public String response(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String temp= null;
        StringBuilder result = new StringBuilder();
        try {
            while ((temp = reader.readLine()) != null) {
                result.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        reader.close();
        @SuppressWarnings("unchecked")
        Map<String,String> map = (Map<String,String>)JSON.parse(result.toString());
        return "Hi, request,I am response, this message is from you: "+map.get("request");
    }

在浏览器输入 localhost:8080/request,然后请求端请求http通信去访问响应端,响应端得到消息后,返回结果,然后请求端得到结果后显示出来

结果:Hi, request,I am response, this message is from you: hi, i am request!

完~

posted @ 2017-12-26 16:33  心之所向,无所不成  阅读(732)  评论(0)    收藏  举报