JAVA發送HttpClient請求及接收請求結果過程

一、寫一個HttpRequestUtils工具類,包括post請求和get請求java

1spring

2express

3apache

4json

5api

6服務器

7app

8工具

9post

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;

    }

}

二、寫業務代碼發送Http請求

三、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>

四、接收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));

    }

}

相關文章
相關標籤/搜索