ORG.APACHE.HTTPCOMPONENTS HTTPCLIENT 发起HTTP JSON请求

1. pom.xml

1

2

3

4

5

<dependency>

    <groupId>org.apache.httpcomponents</groupId>

    <artifactId>httpclient</artifactId>

    <version>4.5.3</version>

</dependency>

2. HttpClient.java

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

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

package com.midea.clean.util;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.Set;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.ParseException;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.methods.HttpUriRequest;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.alibaba.fastjson.JSONObject;

import com.midea.clean.bo.UserBo;

 

public class HttpClient {

     

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);

 

    /**

     * 发送post请求

     * @param url

     * @param params

     * @return

     */

    public static String post(String url, Map<String, String> params) {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        String body = null;

 

        HttpPost post = postForm(url, params);

 

        body = invoke(httpclient, post);

 

        httpclient.getConnectionManager().shutdown();

 

        return body;

    }

 

    /**

     * 发送get请求

     * @param url

     * @return

     */

    public static String get(String url) {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        String body = null;

 

        HttpGet get = new HttpGet(url);

        body = invoke(httpclient, get);

 

        httpclient.getConnectionManager().shutdown();

 

        return body;

    }

 

    private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) {

 

        HttpResponse response = sendRequest(httpclient, httpost);

        String body = paseResponse(response);

 

        return body;

    }

 

    private static String paseResponse(HttpResponse response) {

        HttpEntity entity = response.getEntity();

 

        String charset = EntityUtils.getContentCharSet(entity);

 

        String body = null;

        try {

            body = EntityUtils.toString(entity);

        catch (ParseException e) {

            e.printStackTrace();

        catch (IOException e) {

            e.printStackTrace();

        }

 

        return body;

    }

 

    private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {

        HttpResponse response = null;

 

        try {

            response = httpclient.execute(httpost);

        catch (ClientProtocolException e) {

            e.printStackTrace();

        catch (IOException e) {

            e.printStackTrace();

        }

        return response;

    }

 

    private static HttpPost postForm(String url, Map<String, String> params) {

 

        HttpPost httpost = new HttpPost(url);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        // 需要传一个token

        //httpost.setHeader("token", "c7a4e021-6527-11e6-96be-fcaa14c3021a1");

        Set<String> keySet = params.keySet();

        for (String key : keySet) {

            nvps.add(new BasicNameValuePair(key, params.get(key)));

        }

 

        try {

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

 

        return httpost;

    }

     

     /**

     * post方式提交json代码

     * @throws Exception 

     */ 

    public static String postJson(String url,String json) throws Exception{ 

        //创建默认的httpClient实例.  

        CloseableHttpClient httpclient = null

        //接收响应结果 

        CloseableHttpResponse response = null

        String result = "";

        //创建httppost 

        httpclient = HttpClients.createDefault();   

        HttpPost httpPost = new HttpPost(url); 

        httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); 

        //参数 

        StringEntity se = new StringEntity(json); 

        se.setContentEncoding("UTF-8"); 

        se.setContentType("application/json");//发送json需要设置contentType 

        httpPost.setEntity(se);

        LOGGER.debug("http post url:{},json:{}",url,json);

        response = httpclient.execute(httpPost); 

        LOGGER.debug("http post result:{}", response);

        //解析返结果 

        HttpEntity entity = response.getEntity();  

        if(entity != null){ 

            result = EntityUtils.toString(entity, "UTF-8");  

        

        httpclient.close(); 

        response.close(); 

        return result;

    

 

    public static void main(String[] args) throws Exception {

//      HttpClient.get("http://localhost/clean/4a/welcome");

         

//      Map<String,String> params = new HashMap<String,String>();

//      params.put("empName", "1");

//      params.put("empCode", "2");

//      HttpClient.post("http://localhost/clean/4a/privilege/check", params);

         

        UserBo userBo = new UserBo();

        userBo.setEmpCode("3");

        userBo.setEmpName("zs");

        userBo.setErpUid("4");

        userBo.setMip("5");

        String jsonStr = JSONObject.toJSONString(userBo);

         

        HttpClient.postJson("http://localhost/clean/4a/privilege/check", jsonStr);

    }

     

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpPost是Apache HttpComponents库中的一个类,用于将数据提交到指定的URL。使用HttpPost时,需要先创建一个HttpPost对象并设置请求的URL,然后设置请求数据、请求头部等信息,最后执行请求并获取响应结果。 下面是一个HttpPost的示例代码: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 设置请求头部 httpPost.setHeader("Content-Type", "application/json"); // 设置请求数据 StringEntity entity = new StringEntity(data, Charset.forName("UTF-8")); httpPost.setEntity(entity); // 执行请求并获取响应结果 CloseableHttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8")); httpClient.close(); ``` 使用HttpPost时需要注意以下几点: 1. 设置请求头部时,需要根据实际情况设置Content-Type等参数,否则服务器可能无法正确处理请求。 2. 设置请求数据时,需要注意编码格式,一般使用UTF-8编码。 3. 使用完毕后需要关闭HttpClientHttpResponse对象,以释放资源。 另外,使用HttpPost时可能会遇到一些坑,如: 1. 服务器返回的响应结果可能包含乱码,这时需要根据实际情况设置响应结果的编码格式。 2. 请求数据过大时,可能会导致请求失败,这时可以考虑使用分块请求或压缩数据等方式来解决。 3. 在请求中使用了一些特殊字符(如中文、特殊符号等)时,可能会导致请求失败,这时需要对这些字符进行转义处理。 总体来说,HttpPost是一个非常实用的工具类,需要根据实际情况进行灵活使用和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值