2
sunshine
2024-11-05 d1f9fb55a136e589a5ad588ed9a93ce9272917da
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
/**
 * 
 */
/**
 * @author Administrator
 *
 */
package com.nova.sankuai.infra.utils.baofu;
 
//import com.baofoo.http.*;
//import net.sf.json.JSONObject;
 
import com.alibaba.fastjson.JSONArray;
import com.nova.sankuai.infra.utils.baofu.http.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class HttpUtil {
 
    /**
     * form表单跳转时使用
     * 
     * @param Url
     * @param Parms
     * @return
     */
    public static String HtmlFrom(String Url, Map<String, String> Parms) {
        if (Parms.isEmpty()) {
            return "参数不能为空!";
        }
        String FormString = "<body onLoad=\"document.actform.submit()\">正在处理请稍候.....................<form  id=\"actform\" name=\"actform\" method=\"post\" action=\""
                + Url + "\">";
        for (String key : Parms.keySet()) {
            // Log.Write("HTML:"+key +":"+Parms.get(key));
            FormString += "<input name=\"" + key + "\" type=\"hidden\" value='" + Parms.get(key) + "'>";
        }
 
        FormString += "</form></body>";
        return FormString;
    }
 
    /**
     * 默认application/x-www-form-urlencoded,使用application/json需指定
     * 
     * @param Url
     * @param ContentType
     * @return
     */
    public static String RequestForm(String Url, Map<String, String> Parms, String ContentType) {
        if (Parms.isEmpty()) {
            return "参数不能为空!";
        }
        String PostParms = "";
        int PostItemTotal = Parms.keySet().size();
        int Itemp = 0;
        for (String key : Parms.keySet()) {
            PostParms += key + "=" + Parms.get(key);
            Itemp++;
            if (Itemp < PostItemTotal) {
                PostParms += "&";
            }
        }
        HttpSendModel httpSendModel = new HttpSendModel(Url + "?" + PostParms);
        httpSendModel.setMethod(HttpMethod.POST);
        httpSendModel.setContentTypeStr(ContentType);
        SimpleHttpResponse response = null;
        try {
            response = doRequest(httpSendModel, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return response.getEntityString();
 
    }
 
    public static SimpleHttpResponse doRequest(HttpSendModel httpSendModel, String getCharSet) throws Exception {
 
        // 创建默认的httpClient客户端端
        SimpleHttpClient simpleHttpclient = new SimpleHttpClient();
        try {
            return doRequest(simpleHttpclient, httpSendModel, getCharSet);
        } finally {
            simpleHttpclient.getHttpclient().getConnectionManager().shutdown();
        }
 
    }
 
    /**
     * @param httpSendModel
     * @param getCharSet
     * @return
     * @throws Exception
     */
    public static SimpleHttpResponse doRequest(SimpleHttpClient simpleHttpclient, HttpSendModel httpSendModel,
            String getCharSet) throws Exception {
 
        HttpRequestBase httpRequest = buildHttpRequest(httpSendModel);
 
        if (httpSendModel.getUrl().startsWith("https://")) {
            simpleHttpclient.enableSSL();
        }
        try {
 
            HttpResponse response = simpleHttpclient.getHttpclient().execute(httpRequest);
            int statusCode = response.getStatusLine().getStatusCode();
            if (isRequestSuccess(statusCode)) {
                return new SimpleHttpResponse(statusCode, EntityUtils.toString(response.getEntity(), getCharSet), null);
            } else {
                return new SimpleHttpResponse(statusCode, null, response.getStatusLine().getReasonPhrase());
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("http请求异常", e);
        }
 
    }
 
    /**
     * @param httpSendModel
     * @return
     * @throws Exception
     */
    protected static HttpRequestBase buildHttpRequest(HttpSendModel httpSendModel) throws Exception {
        HttpRequestBase httpRequest;
        if (httpSendModel.getMethod() == null) {
            throw new Exception("请求方式未设定");
        } else if (httpSendModel.getMethod() == HttpMethod.POST) {
 
            String url = httpSendModel.getUrl();
            String sendCharSet = httpSendModel.getCharSet();
            List<HttpFormParameter> params = httpSendModel.getParams();
            Map<String, String> data = new HashMap<String, String>();
            List<NameValuePair> qparams = new ArrayList<NameValuePair>();
            if (params != null && params.size() != 0) {
                for (HttpFormParameter param : params) {
                    data.put(param.getName(), param.getValue());// json方式请求
                    qparams.add(new BasicNameValuePair(param.getName(), param.getValue()));// key/value方式请求
                }
            }
 
            HttpPost httppost = new HttpPost(url);
 
            try {
                if (httpSendModel.getContentTypeStr().isEmpty()) {
                    UrlEncodedFormEntity Str = new UrlEncodedFormEntity(qparams, sendCharSet);
                    httppost.setEntity(Str);
                } else {
//                    StringEntity Str = new StringEntity(JSONObject.fromObject(data).toString(), sendCharSet);
                    StringEntity Str = new StringEntity(JSONArray.toJSON(data).toString(), sendCharSet);
                    Str.setContentEncoding(sendCharSet);
                    Str.setContentType("application/json");
                    httppost.setEntity(Str);
                }
 
            } catch (UnsupportedEncodingException e) {
                throw new Exception("构建post请求参数失败", e);
            }
 
            httpRequest = httppost;
        } else if (httpSendModel.getMethod() == HttpMethod.GET) {
            HttpGet httpget = new HttpGet(httpSendModel.buildGetRequestUrl());
            httpRequest = httpget;
        } else {
            throw new Exception("请求方式不支持:" + httpSendModel.getMethod());
        }
 
        return httpRequest;
    }
 
    /**
     * 请求是否成功
     * 
     * @param statusCode
     * @return
     */
    public static boolean isRequestSuccess(int statusCode) {
        return statusCode == 200;
    }
 
    /**
     * json请求参数有List类型时使用
     * 
     * @param url
     * @param Map<String, Object> params
     * @return
     */
    public static String sendJson(String url, Map<String, Object> params) {
//        Log.Write("【请求Parms】:" + params);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            Object json = JSONArray.toJSON(params);
//            Log.Write("请求参数:" + json);
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentType("application/json");// 发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
//            Log.Write("http响应状态码" + res.getStatusLine().getStatusCode());
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(entity);
//                Log.Write("请求响应结果:" + result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
 
        return null;
    }
 
}