JAVA发送HttpClient请求及接收请求结果过程

下面为本人自己在工作中写业务代码的,并不是通用的,只供自己下次使用时能有个查找地,及正处在困扰中的程序员借鉴。

推荐好点博客给大家看看:

http://blog.sina.com.cn/s/blog_75a8cfac01013aim.html

http://blog.csdn.net/fireelement/article/details/2497136

http://www.2cto.com/kf/201206/136879.html

http://284772894.iteye.com/blog/1744114

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

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扫描目录

<!-- 自动扫描且只扫描@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请求

@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请求

@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));
    }
}
时间: 2024-08-26 01:07:46

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

java 发送http 的get|post 请求

<div> package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public

java 发送POST,DELETE,PATCH,GET请求

import java.io.IOException; import org.apache.commons.codec.CharEncoding; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import

java 发送带cookie的http请求

try{     String path = "https://www.AA.com/AA";         URL url = new URL(path);         HttpURLConnection con = (HttpURLConnection) url.openConnection();         con.setRequestMethod("GET");         /*con.setRequestProperty("Cont

JAVA发送http post 请求、get请求

1.写一个HttpRequestUtils工具类,包括post请求和get请求 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

用JAVA发送一个XML格式的HTTP请求

1 import java.io.BufferedInputStream; 2 import java.io.BufferedReader; 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStreamWriter; 8 impo

Java使用HttpClient实现Post请求

基于项目需求,想要实现Post消息推送,故采用HttpClient组件进行实现,相关代码如下(注:程序采用的httpclient和httpcore依赖包的版本为4.2.5): import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache

httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求

1.httpclient就是个能发送http连接的工具包,包括能发送post请求和get请求. http 连接一次就有返回流.http是个双向的嘛.只有连接了,就会有输出返回流. 所以在执行http连接的时候,返回值都是http连接的返回流. HttpResponse response = client.execute(httpPost); 2.http发送,body里是可以写入中文的.但要注意乱码问题: public static String getHttpRequestString(Str

Java发送http get/post请求,调用接口/方法

由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong    转自:http://blog.csdn.net/capmiachael/article/details/51833531 例1:使用 HttpClient (commons-httpclient-3.0.jar 1 import java.io.ByteArrayInputStream; 2 import java.io.ByteArrayOutputStream; 3

Java发送HTTPS请求

前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊,我也是踩过坑的,所以我这个工具,只要粘贴到你们自己项目里就可以用.我的工具跟网上没什么区别,唯一的区别是我亲身实战过,把需要注意的细节列出来,不让大家浪费时间.   正文 本文只介绍 发送 post 请求,既然选择了 https 就不会用get,因为get也是不安全的.   读前须知 我会把需要依赖