Java tutorial
/** * Copyright (C) 2015. Keegan?http://keeganlee.me * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.huixueyun.tifenwang.api.net; import com.huixueyun.tifenwang.api.ApiModel; import com.huixueyun.tifenwang.api.ApiResponse; import com.huixueyun.tifenwang.model.utils.L; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Http? * * @version 1.0 * @date 16/3/2 */ public class HttpEngine { //? public final static String LOGIN_URL = "xitong/userLogin_app.php"; //? public final static String REGISTER_URL = "xitong/userRegisterApp.php"; //? public final static String BEHAVIOR_URL = ""; //http? public final static String RESPONSE_TYPE_JSON = "json"; //Tag private final static String TAG = "HttpEngine"; //?? private final static String SERVER_URL = "http://api.huixueyuan.cn/ifdood_dev01/v2/"; //http private final static String REQUEST_MOTHOD = "POST"; //?? private final static String ENCODE_TYPE = "UTF-8"; // private final static short TIME_OUT = 3000; //HttpEngine private static HttpEngine instance = null; // private HttpEngine() { } //HttpEngine? public static HttpEngine getInstance() { if (instance == null) { synchronized (HttpEngine.class) { if (instance == null) instance = new HttpEngine(); } } return instance; } /** * http urlconnection? * * @param paramsMap ?? * @param model ? * @param paramUrl ?? * @param type ? * @param <T> * @return ApiResponse? * @throws IOException */ public <T> T postConnectionHandle(Map<String, String> paramsMap, String model, String paramUrl, String type) throws IOException { String data = joinParams(paramsMap, type); // ? L.e(data); HttpURLConnection connection = getConnection(paramUrl); connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length)); connection.connect(); OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); if (connection.getResponseCode() == 200) { // ??? InputStream is = connection.getInputStream(); // ? ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ? int len = 0; // byte buffer[] = new byte[1024]; // ?? while ((len = is.read(buffer)) != -1) { // ??os baos.write(buffer, 0, len); } // ? is.close(); baos.close(); connection.disconnect(); // final String result = new String(baos.toByteArray()); ApiResponse apiResponse; try { apiResponse = ApiModel.getInstance().getApiResponse(model, result); } catch (Exception e) { apiResponse = null; } return (T) apiResponse; } else { connection.disconnect(); return null; } } /** * http client * * @param paramsMap ?? * @param model ? * @param paramUrl ?? * @param type ? * @param <T> * @return ApiResponse? * @throws IOException */ public <T> T postClientHandle(Map<String, String> paramsMap, String model, String paramUrl, String type) throws IOException { String data = joinParams(paramsMap, type); // ? L.e(data); String uriAPI = SERVER_URL + paramUrl; /*HTTP Post*/ HttpPost httpRequest = new HttpPost(uriAPI); HttpParams httpparams = new BasicHttpParams(); /* */ /* ? */ ConnManagerParams.setTimeout(httpparams, TIME_OUT); /* */ HttpConnectionParams.setConnectionTimeout(httpparams, TIME_OUT); /* */ HttpConnectionParams.setSoTimeout(httpparams, TIME_OUT); HttpClient httpclient = new DefaultHttpClient(httpparams); //Post???NameValuePair[] //? ??request.getParameter("name") List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("json", data.substring(type.length() + 1))); //?HTTP request httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //?HTTP response HttpResponse httpResponse = httpclient.execute(httpRequest); //??200 ok if (httpResponse.getStatusLine().getStatusCode() == 200) { //? String result = EntityUtils.toString(httpResponse.getEntity()); ApiResponse apiResponse; try { apiResponse = ApiModel.getInstance().getApiResponse(model, result); } catch (Exception e) { apiResponse = null; } return (T) apiResponse; } else { return null; } } /** * ?connection * * @param paramUrl ?? * @return HttpURLConnection */ private HttpURLConnection getConnection(String paramUrl) { HttpURLConnection connection = null; // ?connection try { // ??URL URL url = new URL(SERVER_URL + paramUrl); // ?URL connection = (HttpURLConnection) url.openConnection(); // ? connection.setRequestMethod(REQUEST_MOTHOD); // ??POST?true connection.setDoInput(true); // ??POST? connection.setDoOutput(true); // ? connection.setUseCaches(false); // connection.setReadTimeout(TIME_OUT); connection.setConnectTimeout(TIME_OUT); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Response-Type", "json"); connection.setChunkedStreamingMode(0); } catch (IOException e) { e.printStackTrace(); } return connection; } /** * ? * * @param paramsMap ?? * @param jsonKey ? * @return ? */ private String joinParams(Map<String, String> paramsMap, String jsonKey) { if (jsonKey.equals(RESPONSE_TYPE_JSON)) { //json?jsonobject JSONObject object = new JSONObject(); try { for (String key : paramsMap.keySet()) { object.put(key, paramsMap.get(key)); } } catch (Exception e) { e.printStackTrace(); } return jsonKey + "=" + object.toString(); } else { //??json? StringBuilder stringBuilder = new StringBuilder(); for (String key : paramsMap.keySet()) { stringBuilder.append(key); stringBuilder.append("="); try { stringBuilder.append(URLEncoder.encode(paramsMap.get(key), ENCODE_TYPE)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } stringBuilder.append("&"); } return stringBuilder.substring(0, stringBuilder.length() - 1); } } }