1、写一个HttpRequestUtils工具类,包括post请求和get请求

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.brainlong.framework.util.httpclient;
 
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.IOException;
import java.net.URLDecoder;
 
public class HttpRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
 
    /**
     * httpPost
     * @param url  路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam){
        return httpPost(url, jsonParam, false);
    }
 
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功,并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.fromObject(str);
                catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }
 
 
    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpGet(String url){
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功,并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            else {
                logger.error("get请求提交失败:" + url);
            }
        catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }
}

2、写业务代码发送Http请求

3、MVC配置文件设置Controller扫描目录

1
2
3
4
<!-- 自动扫描且只扫描@Controller -->
<context:component-scan base-package="com.wiselong.multichannel" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

4、接收Http请求

接收post请求

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
@Controller
@RequestMapping(value = "/api/platform/exceptioncenter/exceptioninfo")
public class ExceptionInfoController {
    //注入
    @Autowired
    private ExceptionInfoBiz exceptionInfoBiz;
 
    /**
     * 创建异常信息请求
     * @param requestBody 请求消息内容
     * @param request 请求消息头
     * @return jsonObject
     */
    @RequestMapping(
            value="/create",
            method = RequestMethod.POST
    )
    public ModelAndView createExceptionInfo(@RequestBody String requestBody, HttpServletRequest request) {
        JSONObject jsonObject = JSONObject.fromObject(requestBody);
        ComExceptionInfo comExceptionInfo = new ComExceptionInfo();
        comExceptionInfo.setProjectName(jsonObject.getString("projectName"));
        comExceptionInfo.setTagName(jsonObject.getString("tagName"));
        exceptionInfoBiz.insert(comExceptionInfo);
        //返回请求结果
        JSONObject result= new JSONObject();
        result.put("success""true");
        return new ModelAndView("", ResponseUtilsHelper.jsonSuccess(result.toString()));
    }
  }

接收get请求

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
@Controller
@RequestMapping(value="/api/platform/messagecenter/messages/sms")
public class SmsController {
    @Autowired
    SmsSendBiz smsSendBiz;
 
    /**
     * 接收手机号码和内容往短信发送表插入一条记录
     * @param requestbody 请求消息内容
     * @param request 请求消息头
     * @return jsonObject
     */
    @RequestMapping(
            value="/send",
            method= RequestMethod.GET
    )
    public ModelAndView sendSms(@RequestBody String requestbody, HttpServletRequest request) {
        //获取请求URL及url后面传输的参数
        String url = request.getRequestURL() + "?" + request.getQueryString();
        url = BuildRequestUrl.decodeUrl(url);
        String telePhone = RequestUtils.getStringValue(request, "telePhone");
        String content = RequestUtils.getStringValue(request, "content");
        smsSendBiz.insertTtMsQuequ(telePhone,content);
        return new ModelAndView("", ResponseUtilsHelper.jsonResult(""true));
    }
}

JAVA发送HttpClient请求及接收请求结果过程的更多相关文章

  1. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  2. 【commons-httpclient】Java中HttpClient工具访问Web请求

    注意jar包是: HttpClient工具使用 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程 ...

  3. java 发送http 的get|post 请求

    <div>  package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import jav ...

  4. java发送http的get/post请求(一)

    HTTP请求类 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; ...

  5. JAVA发送HttpClient

    http://bijian1013.iteye.com/blog/2310211 在发送HTTP请求的时候会使用到POST和GET两种方式,如果是传送普通的表单数据,我们直接将参数到一个Key-val ...

  6. java 发送 http post 和 get 请求(利用unirest)

    调用服务器端的接口在前端调用,但是我们也会经常遇到在服务器后端调用接口的情况,网上的例子大部分都是用 jdk 原生的 URL realUrl = new URL(url); URLConnection ...

  7. JAVA发送xml格式的接口请求

    /** * * @param urlStr 接口地址 * @param xmlInfo xml格式参数数据 * @return */ public static String sendMsgXml(S ...

  8. java使用HttpClient

    HttpClient常用的包有两个 org.apache.http.client以及org.apache.commons.httpclient 我常用的是org.apache.http.client. ...

  9. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

随机推荐

  1. 一个5.0/3.3V双向通讯的电路

    来自群友 西江月-梧州 的分享 硬件程工-深圳福永(79993868) 17:06:33 当3.3V高时二极管阳极为3.3V,阴极接了10K上拉为5V,二极管的压降为反向,此时二极管不导通. 硬件程工 ...

  2. Notepad++ 删除空白行的方法

    Notepad++ 是我特别喜欢的一款编程工具.在安装后就可以轻松使用了.Notepad++ 上提供了很多方便的插件以实现更多的扩展,当然自身已经比较强大好用了.如果你遇到文本中间有大量的空白行的话, ...

  3. MySQL索引分类和各自用途

    一. MySQL: 索引以B树格式保存 Memory存储引擎可以选择Hash或BTree索引,Hash索引只能用于=或<=>的等式比较. 1.普通索引:create index on Ta ...

  4. Redis内存数据库操作命令详解

    一.连接操作相关的命令 Ÿ   quit:关闭连接(connection) Ÿ   auth:简单密码认证 二.对value操作的命令 Ÿ   exists(key):确认一个key是否存在 Ÿ   ...

  5. bzoj1833 数字计数

    Description 给定两个正整数a和b,求在[a,b]中的所有整数中,每个数码(digit)各出现了多少次. Input 输入文件中仅包含一行两个整数a.b,含义如上所述. Output 输出文 ...

  6. jquery.cookie.js $.cookie()是怎么使用

    jquery.cookie() 方法的使用(读取.写入.删除) <script type="text/javascript" src="js/jquery.cook ...

  7. uploadify是通过flash上传,服务器获取type为application/octet-stream

    uploadify是通过flash上传,服务器获取type为application/octet-stream,因此允许上传的类型要加上application/octet-stream

  8. 浅析HttpCient

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java.net 包中已经提供了 ...

  9. JedisCluster模式尝试进行批量操作

    搭建完redis集群后,可以通过jedis的JedisCluster来访问Redis集群,这里列出使用jedisCluster的spring bean配置方式:   <bean id=" ...

  10. mysql响应时间超时排查

    背景: 数据库运营环境,zabbix mysql响应时间告警,响应时间超时 zabbix监控 tcprstart 直接抓包响应时间看到每5秒钟就一次,与zabbix监控一致 [root@slave1( ...