Java tutorial
/* * Copyright 2010 Renren, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lostad.app.base.util; import com.google.gson.Gson; 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.HttpClient; 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.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.List; import java.util.Map; /** * ? * @author sszvip@qq.com * @since 2013-7-2 */ public class RequestUtil { public static String getRequest(final String url, String token, final boolean isSingleton) throws Exception { String json = null; HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpGet get = new HttpGet(url); if (Validator.isNotEmpty(token)) { get.addHeader("token", token); } try { //long t1 = System.currentTimeMillis(); HttpResponse response = client.execute(get, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 //? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (get != null) { get.abort(); } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); } return json; }// end method submitForm public static String postRequest(final String url, final StringEntity params, String token, final boolean isSingleton) throws Exception { String json = null; HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPost post = new HttpPost(url); if (Validator.isNotEmpty(token)) { post.addHeader("token", token); } try { //long t1 = System.currentTimeMillis(); if (params != null) { params.setContentEncoding(HTTP.UTF_8); params.setContentType("application/x-www-form-urlencoded"); post.setEntity(params); } HttpResponse response = client.execute(post, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 //? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (post != null) { post.abort(); } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); } return json; }// end method submitForm public static String postForm(String url, List<NameValuePair> params, boolean isSingleton) throws Exception { String json = null; HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPost post = new HttpPost(url); try { if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); post.setEntity(entity); } HttpResponse response = client.execute(post, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 // ? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (post != null) { post.abort();// } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent();//? } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); ///client.getConnectionManager().shutdown(); } return json; } public static String putForm(String url, List<NameValuePair> params, String token, boolean isSingleton) throws Exception { String json = null; HttpClient client = HttpClientManager.getHttpClient(isSingleton); HttpEntity resEntity = null; HttpPut put = new HttpPut(url); put.addHeader("token", token); try { put.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); if (params != null) { entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("application/x-www-form-urlencoded"); } put.setEntity(entity); } HttpResponse response = client.execute(put, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 // ? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (put != null) { put.abort();// } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent();//? } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); ///client.getConnectionManager().shutdown(); } return json; } public static String postJson(String url, String token, Object obj) throws Exception { Gson g = new Gson(); String json = g.toJson(obj); return postJson(url, token, json); } public static String postJson(String url, String token, String dataJson) throws Exception { String json = null; HttpEntity resEntity = null; HttpClient client = HttpClientManager.getHttpClient(true); HttpPost post = new HttpPost(url); if (Validator.isNotEmpty(token)) { post.addHeader("token", token); } try { post.addHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity se = new StringEntity(dataJson, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); // HttpResponse response = client.execute(post, new BasicHttpContext()); resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200 // ? json = EntityUtils.toString(resEntity); } } catch (Exception e) { if (post != null) { post.abort();// } throw e; } finally { if (resEntity != null) { try { resEntity.consumeContent();//? } catch (IOException e) { e.printStackTrace(); } } client.getConnectionManager().closeExpiredConnections(); ///client.getConnectionManager().shutdown(); } return json; } /** * HTTP??????,??? * @param actionUrl * @param params ? key???,value? * @param files * @throws Exception */ public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token) throws Exception { try { String BOUNDARY = "---------7d4a6d158c9"; //? String MULTIPART_FORM_DATA = "multipart/form-data"; URL url = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//? conn.setDoOutput(true);//? conn.setUseCaches(false);//?Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); conn.setRequestProperty("token", token); //???? StringBuilder sb = new StringBuilder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) {//? sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); sb.append(entry.getValue()); sb.append("\r\n"); } } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes());//???? //?? for (FormFile file : files) { StringBuilder split = new StringBuilder(); split.append("--"); split.append(BOUNDARY); split.append("\r\n"); split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\"" + file.getFilname() + "\"\r\n"); split.append("Content-Type: " + file.getContentType() + "\r\n\r\n"); outStream.write(split.toString().getBytes()); outStream.write(file.getData(), 0, file.getData().length); outStream.write("\r\n".getBytes()); } byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//?? outStream.write(end_data); outStream.flush(); int cah = conn.getResponseCode(); if (cah != 200) throw new RuntimeException("url"); InputStream is = conn.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } outStream.close(); conn.disconnect(); return b.toString(); } catch (Exception e) { throw e; } } //SSL /** * PostHttps? * @param url; ? * @param json * @return * @throws Exception */ public static synchronized String postHttps(String url, String json) throws Exception { // ? HttpParams httpParameters = new BasicHttpParams(); // HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); // socket HttpConnectionParams.setSoTimeout(httpParameters, 3000); // ?HttpClient ? HttpClient hc = HttpClientManager.getHttpClientSSL(httpParameters); HttpPost post = new HttpPost(url); // ??? post.addHeader("Content-Type", "application/json;charset=utf-8"); // ?? post.addHeader("Accept", "application/json"); // StringEntity entity = new StringEntity(json, "UTF-8"); post.setEntity(entity); post.setParams(httpParameters); HttpResponse response = null; try { response = hc.execute(post); } catch (UnknownHostException e) { throw new Exception("Unable to access " + e.getLocalizedMessage()); } catch (SocketException e) { e.printStackTrace(); } int sCode = response.getStatusLine().getStatusCode(); if (sCode == HttpStatus.SC_OK) { return EntityUtils.toString(response.getEntity()); } else throw new Exception("StatusCode is " + sCode); } }