Java HttpClient

时间:2021-07-28 06:10:43
public class WebClient {

    public static final String POST_TYPE_JSON = "json";
public static final String POST_TYPE_MULTI = "multi";
public static final String POST_TYPE_NAME_VALUE = "name_value";
private static final Pattern pageEncodingReg = Pattern.compile("content-type.*charset=([^\">\\\\]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern headerEncodingReg = Pattern.compile("charset=(.+)", Pattern.CASE_INSENSITIVE); private DefaultHttpClient httpClient = new DefaultHttpClient();
private String url;
private HTTPMethod method;
private Response response;
private Map<String, String> headers = new HashMap<String, String>();
private JSONObject parameters = new JSONObject();
private List<FormBodyPart> multipartParameter = new ArrayList<FormBodyPart>();
private String postType; private static final String UTF8 = "utf-8"; public void setMethod(HTTPMethod method) {
this.method = method;
} public void setUrl(String url) {
if (isStringEmpty(url)) {
throw new RuntimeException("[Error] url is empty!");
}
this.url = url;
headers.clear();
parameters.clear();
multipartParameter.clear();
postType = null;
response = null; if (url.startsWith("https://")) {
enableSSL();
} else {
disableSSL();
}
} public Map<String, String> getRequestHeaders() {
return headers;
} public void setRequestHeaders(String key, String value){
headers.put(key, value);
} public void addParameter(String name, Object value){
parameters.put(name, value);
} public void setParameters(JSONObject json){
parameters.clear();
parameters.putAll(json);
} public void setAjaxHeaders(){
setRequestHeaders("Content-Type", "application/json");
} public void setTimeout(int connectTimeout, int readTimeout) {
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
HttpConnectionParams.setSoTimeout(params, readTimeout);
} public Response sendRequest() throws IOException {
if (url == null || method == null) {
throw new RuntimeException("Request exception: URL or Method is null");
} httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse resp = null;
HttpUriRequest req = null; if (method.equals(HTTPMethod.GET)) {
req = new HttpGet(url);
}
else if(method.equals(HTTPMethod.DELETE)){
req = new HttpDelete(url);
}
else if(method.equals(HTTPMethod.PUT)){
req = new HttpPut(url);
if(parameters.size() > 0){
StringEntity entity = new StringEntity(new String(parameters.toString().getBytes("utf-8"), "ISO-8859-1"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
((HttpPut) req).setEntity(entity);
}
}
else {
req = new HttpPost(url); if(POST_TYPE_MULTI.equals(postType) ){
MultipartEntity entity = new MultipartEntity();
for(FormBodyPart bodyPart : multipartParameter){
entity.addPart(bodyPart);
}
((HttpPost) req).setEntity(entity);
}
else if(parameters.size() > 0){
if(POST_TYPE_JSON.equals(postType)){
StringEntity entity = new StringEntity(new String(parameters.toString().getBytes("utf-8"), "ISO-8859-1"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
((HttpPost) req).setEntity(entity);
}
else{
Iterator<String> iterator = parameters.keys();
List<NameValuePair> postParameter = new ArrayList<NameValuePair>();
while(iterator.hasNext()){
String key = iterator.next();
postParameter.add(new BasicNameValuePair(key, parameters.getString(key)));
}
((HttpPost) req).setEntity(new UrlEncodedFormEntity(postParameter, UTF8));
}
}
}
for (Entry<String, String> e : headers.entrySet()) {
req.addHeader(e.getKey(), e.getValue());
}
req.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
resp = httpClient.execute(req);
Header[] header = resp.getAllHeaders();
Map<String, String> responseHeaders = new HashMap<String, String>();
for (Header h : header) {
responseHeaders.put(h.getName(), h.getValue());
}
response = new Response();
response.setCode(resp.getStatusLine().getStatusCode());
response.setHeaders(responseHeaders);
String content = getContent(EntityUtils.toByteArray(resp.getEntity()));
response.setContent(content);
return response;
} private boolean isStringEmpty(String s) {
return s == null || s.length() == 0;
} private String getContent(byte[] bytes) throws IOException {
if (bytes == null) {
throw new RuntimeException("[Error] Can't fetch content!");
}
String headerContentType = null;
if ((headerContentType = response.getHeaders().get("Content-Type")) != null) {
Matcher m1 = headerEncodingReg.matcher(headerContentType);
if (m1.find()) {
return new String(bytes, m1.group(1));
}
} String html = new String(bytes);
Matcher m2 = pageEncodingReg.matcher(html);
if (m2.find()) {
html = new String(bytes, m2.group(1));
}
return html;
} private void enableSSL() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", sf, 443);
httpClient.getConnectionManager().getSchemeRegistry().register(https);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} private void disableSSL() {
SchemeRegistry reg = httpClient.getConnectionManager().getSchemeRegistry();
if (reg.get("https") != null) {
reg.unregister("https");
}
} public DefaultHttpClient getHttpClient() {
return httpClient;
} public enum HTTPMethod {
GET, POST, DELETE, PUT
} // SSL handler (ignore untrusted hosts)
private static TrustManager truseAllManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}; public void setPostType(String postType) {
this.postType = postType;
} public void setMultipartParameter(List<FormBodyPart> multipartParameter) {
this.multipartParameter.clear();
this.multipartParameter.addAll(multipartParameter);
}
}