dhz
2022-06-22 06856202544f4324e27896e8a7b2fcf1298f5c68
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package cn.ksource.core.util;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
 
public class HttpUtil {
    
    public final static Logger logger = Logger.getLogger(HttpUtil.class);
    
    /**
     * use doGet() 
     *     通过Http Get协议访问网址,并返回内容
     * @param strUrl
     * @return
     */
    @Deprecated
    public static String getContentForGet(String strUrl){
        try {
            // 创建url对象
            URL url = new URL(strUrl);
            // 打开url连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置url请求方式 ‘get’ 或者 ‘post’
            connection.setRequestMethod("GET");
            // 发送
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer=new StringBuffer();
            int ch=0;
            while((ch=in.read())!=-1)
            buffer.append((char)ch);
            in.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    
    /**
     * 使用Http Post协议访问URL
     * @param url 要访问的URL
     * @param params 参数
     * @param charset 字符集
     * @return
     */
    public static String  doPostUseJsonParams(String url,Map<String, String> paramValues,HttpCharset charset) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpost = new HttpPost(url);
            
            //===========================================================
            //数据以json格式传输,所以这里加了通用限制  by jiangxiaolei  2014-05-05
            Map<String,String> params = new HashMap<String,String>();
            params.put("params", JsonUtil.map2Json(paramValues));
            //===========================================================
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            
            String param = "";
            if (params != null && !params.isEmpty()) {
                for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {
                    String key = (String)iterator.next();
                    nvps.add(new BasicNameValuePair(key, params.get(key)));
                    param += key + "=" + params.get(key) + ";";
                }
            }
 
            logger.info("Http Post :" + url+"\n" + param);
            
            httpost.setEntity(new UrlEncodedFormEntity(nvps,charset.toString()));
 
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(),charset.toString()));
            StringBuffer buffer=new StringBuffer();
            int ch=0;
            while((ch=in.read())!=-1)
            buffer.append((char)ch);
            in.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return "";
    }
    
    /**
     * 使用Http Get协议访问URL
     * @param url 要访问的URL,不带问号”?“
     * @param params 参数
     * @param charset 字符集
     * @return
     * @throws HttpRemoteException 
     */
    public static String  doGetUseJsonParams(String url,Map<String, String> paramValues,HttpCharset charset) throws HttpRemoteException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            //===========================================================
            //数据以json格式传输,所以这里加了通用限制  by jiangxiaolei  2014-05-05
            Map<String,String> params = new HashMap<String,String>();
            params.put("params", JsonUtil.map2Json(paramValues));
            //===========================================================
            String param = "";
            if (params != null && !params.isEmpty()) {
                for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {
                    String key = (String)iterator.next();
                    param += "&"+key +"=" + params.get(key);
                }
                param = StringUtils.removeStart(param, "&");
                param = "?"+param;
            }
            
            String myurl = url+param;
            
            logger.info("Http Get :" + myurl );
            
            HttpGet httpost = new HttpGet(myurl);
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(),charset.toString()));
            StringBuffer buffer=new StringBuffer();
            int ch=0;
            while((ch=in.read())!=-1)
            buffer.append((char)ch);
            in.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRemoteException(e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    
    
    /**
     * 使用Http Post协议访问URL
     * @param url 要访问的URL
     * @param params 参数
     * @param charset 字符集
     * @return
     */
    public static String  doPost(String url,Map<String, String> params,HttpCharset charset) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpost = new HttpPost(url);
            
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            
            String param = "";
            if (params != null && !params.isEmpty()) {
                for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {
                    String key = (String)iterator.next();
                    nvps.add(new BasicNameValuePair(key, params.get(key)));
                    param += key + "=" + params.get(key) + ";";
                }
            }
 
            logger.info("Http Post :" + url+"\n" + param);
            
            httpost.setEntity(new UrlEncodedFormEntity(nvps,charset.toString()));
 
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(),charset.toString()));
            StringBuffer buffer=new StringBuffer();
            int ch=0;
            while((ch=in.read())!=-1)
            buffer.append((char)ch);
            in.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
        return "";
    }
    
    /**
     * 使用Http Get协议访问URL
     * @param url 要访问的URL,不带问号”?“
     * @param params 参数
     * @param charset 字符集
     * @return
     * @throws HttpRemoteException 
     */
    public static String  doGet(String url,Map<String, String> params,HttpCharset charset) throws HttpRemoteException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            String param = "";
            if (params != null && !params.isEmpty()) {
                for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {
                    String key = (String)iterator.next();
                    param += "&"+key +"=" + params.get(key);
                }
                param = StringUtils.removeStart(param, "&");
                param = "?"+param;
            }
            
            String myurl = url+param;
            
            logger.info("Http Get :" + myurl);
            
            HttpGet httpost = new HttpGet(myurl);
            HttpResponse response = httpclient.execute(httpost);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(),charset.toString()));
            StringBuffer buffer=new StringBuffer();
            int ch=0;
            while((ch=in.read())!=-1)
            buffer.append((char)ch);
            in.close();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new HttpRemoteException(e.getMessage());
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    
    
    /**
     * 以POST方式发送内容体
     * @param targetUrl
     * @param content
     * @param charset
     * @version V1.0.0
     * @author 杨凯
     * @date Feb 10, 2015 11:21:27 AM
     */
    public static String doPost(String targetUrl,String content,HttpCharset charset){
        try { 
            // 建立连接 
            URL url = new URL(targetUrl); 
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 
    
            // //设置连接属性 
            httpConn.setDoOutput(true);// 使用 URL 连接进行输出 
            httpConn.setDoInput(true);// 使用 URL 连接进行输入 
            httpConn.setUseCaches(false);// 忽略缓存 
            httpConn.setRequestMethod("POST");// 设置URL请求方法 
    
             
            // 设置请求属性 
            // 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致 
            byte[] requestStringBytes = content.getBytes(charset.toString()); 
            httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length); 
            httpConn.setRequestProperty("Content-Type", "application/octet-stream"); 
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 
            httpConn.setRequestProperty("Charset", "UTF-8"); 
            // 
//            String name = URLEncoder.encode("黄武艺", "utf-8"); 
//            httpConn.setRequestProperty("NAME", name); 
    
             
            // 建立输出流,并写入数据 
            OutputStream outputStream = httpConn.getOutputStream(); 
            outputStream.write(requestStringBytes); 
            outputStream.close(); 
            // 获得响应状态 
            int responseCode = httpConn.getResponseCode(); 
    
             
            if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功 
            // 当正确响应时处理数据 
            StringBuffer sb = new StringBuffer(); 
            String readLine; 
            BufferedReader responseReader; 
            // 处理响应流,必须与服务器响应流输出的编码一致 
             responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), charset.toString())); 
            while ((readLine = responseReader.readLine()) != null) { 
                sb.append(readLine).append("\n"); 
                } 
                responseReader.close(); 
                return sb.toString();
            } 
        } catch (Exception ex) { 
        ex.printStackTrace(); 
        } 
 
         return "";
        } 
    
    public static void main(String[] args) {
        System.out.println(System.getProperties().getProperty("os.name"));
    }
    
}