Java tutorial
/** * Copyright (C) 2012 TookitForAndroid Project * * 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 test; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; /** * * :TODO<br/> * ??:TODO<br/> * 2015-4-20?1:35:00<br/> * majun<br/> * ?:<a href="mailto:747673016@qq.com">@author majun</a><br/> * ======================================================<br/> * ?Copyright 2011 ?? ??<br/> * ======================================================<br/> */ public class Http { private static final String TAG = Http.class.getSimpleName(); /** * <b>description :</b> ????POST?? </br><b> * * * @param url * POSTURL * @param params * POSTURL * @return ??? * @throws MalformedURLException * @throws IOException */ public static InputStream post(String url, Map<String, String> params) throws MalformedURLException, IOException { return post(url, params, null); } /** * <b>description :</b> ????POST?? </br><b> * * * @param url * POSTURL * @param params * POST? * @param data * ???? * @return ??? * @throws MalformedURLException * @throws IOException */ public static InputStream post(String url, Map<String, String> params, byte[] data) throws MalformedURLException, IOException { if (null != params) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()); sb.append("&"); } String param = sb.deleteCharAt(sb.length() - 1).toString(); return connect("POST", new URL(url), param.getBytes(), data); } else { return connect("POST", new URL(url), null, data); } } /** * <b>description :</b> ????POST?? </br><b> * * * @param method * ?? * @param url * POSTURL * @param datas * ???? * @return ??? * @throws IOException */ private static InputStream connect(String method, URL url, byte[]... datas) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setConnectTimeout(6 * 1000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); OutputStream outputStream = conn.getOutputStream(); for (byte[] data : datas) { outputStream.write(data); } outputStream.close(); return conn.getInputStream(); } /** * <b>description :</b> ????GET?? </br><b> * * * @param url * GETURL * @param params * ???? * @return ??? * @throws MalformedURLException * @throws IOException */ public static InputStream get(String url, Map<String, String> params) throws MalformedURLException, IOException { if (null != params) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()); sb.append("&"); } String param = sb.deleteCharAt(sb.length() - 1).toString(); return connect("GET", new URL(url), param.getBytes()); } return connect("GET", new URL(url), new byte[] {}); } /** * <b>description :</b> ????GET?? </br><b> * * * @param url * GETURL * @return ??? * @throws MalformedURLException * @throws IOException */ public static InputStream get(String url) throws MalformedURLException, IOException { return get(url, null); } /** * post url :??jsonString???json,?json * * @date * @param url * @param jsonString * @return * @throws Exception */ public static String httpPost1(String url, String jsonString) throws Exception { String responseBodyData = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // ? // httpPost.addHeader("Content-Type", // "application/x-www-form-urlencoded"); httpPost.addHeader("Content-Type", "text/html"); httpPost.getParams().setParameter("http.socket.timeout", new Integer(60000)); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5); // Log.i(TAG, jsonString); // byte[] requestStrings = jsonString.getBytes("UTF-8"); ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestStrings); httpPost.setEntity(byteArrayEntity); HttpResponse response = httpClient.execute(httpPost);// post try { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { } HttpEntity entity = response.getEntity(); if (entity != null) { responseBodyData = EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { // throw new Exception(e); e.printStackTrace(); } finally { httpPost.abort(); httpClient = null; } return responseBodyData; } /** * post url :??jsonString???json,?json * * @date * @param url * @param jsonString * @return * @throws Exception */ public static String httpPostWithJson(String url, String jsonString) { String result = ""; DefaultHttpClient httpClient = new DefaultHttpClient(); // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000); // ? httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000); HttpPost httpPost = new HttpPost(url); // ??? try { StringEntity reqEntity = new StringEntity(jsonString, HTTP.UTF_8); httpPost.setHeader("Content-type", "text/xml; charset=utf-8"); // ? httpPost.setEntity(reqEntity); HttpResponse response = httpClient.execute(httpPost);// post HttpEntity entity = response.getEntity(); // BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); String line = null; result = ""; while ((line = reader.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } return result; } /** * post url :??jsonString???json,?json * * @date * @param url * @param jsonString * @return * @throws Exception */ public static String httpPostWithJsons(String url, String jsonString) throws Exception { System.out.println("==url++" + url + "==jsonString" + jsonString); String responseBodyData = null; HttpClient httpClient = new DefaultHttpClient(); // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000); // ? httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "text/html"); // byte[] requestStrings = jsonString.toString().getBytes("UTF-8"); ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestStrings); httpPost.setEntity(byteArrayEntity); try { HttpResponse response = httpClient.execute(httpPost);// post if (response.getStatusLine().getStatusCode() == 200) { responseBodyData = EntityUtils.toString(response.getEntity()); } else { responseBodyData = null; } } catch (Exception e) { } finally { httpPost.abort(); httpClient = null; } return responseBodyData; } /** * ?url?? * * @param url * @return */ public static String HttpPost2(String url) { String responseBodyData = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // ? httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.getParams().setParameter("http.socket.timeout", new Integer(60000)); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 5); try { HttpResponse response = httpClient.execute(httpPost);// post if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { } HttpEntity entity = response.getEntity(); if (entity != null) { responseBodyData = EntityUtils.toString(entity, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { httpPost.abort(); httpClient = null; } return responseBodyData; } public static String submit(String url, String requestJson, List<File> upFiles) { String result = ""; System.out.println("json:" + requestJson); HttpClient httpclient = new DefaultHttpClient(); InputStream instream = null; try { HttpPost httpPost = new HttpPost(url); // MultipartEntity multipartEntity = new MultipartEntity(); // multipartEntity.addPart("requestJson", new StringBody(requestJson, // Charset.forName("UTF-8"))); // for (File file : upFiles) { // FileBody fileBody = new FileBody(file); // multipartEntity.addPart("file", (ContentBody) fileBody); // } // httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpclient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { instream = httpEntity.getContent(); // BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); String line = null; result = ""; while ((line = reader.readLine()) != null) { result += line; } } } } catch (IOException e) { e.printStackTrace(); } finally { if (instream != null) { try { instream.close(); } catch (IOException e) { e.printStackTrace(); } } httpclient.getConnectionManager().shutdown(); } return result; } public static String postRequest(String url, String reqJson) { String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpEntity httpEntity = null; try { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("requestJson", reqJson)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); HttpResponse httpResponse = httpclient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { httpEntity = httpResponse.getEntity(); if (httpEntity != null) { // BufferedReader reader = new BufferedReader( new InputStreamReader(httpEntity.getContent(), "UTF-8")); String line = null; result = ""; while ((line = reader.readLine()) != null) { result += line; } } } } catch (IOException e) { if (httpEntity != null) { try { String returnJson = EntityUtils.toString(httpEntity); result = returnJson; } catch (ParseException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return result; } public static void postRequestN(String reqJson, String url) { System.out.println("json:" + reqJson); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("requestJson", reqJson)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); HttpResponse httpResponse = httpclient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String returnJson = EntityUtils.toString(httpEntity); System.out.println("?json:" + returnJson); // EntityUtils.consume(httpEntity); } } } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } } }