1. compile 'com.loopj.android:android-async-http:1.4.9':
AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8"); params.put("loginer_id", "4363"); params.put("tzcodelist", "0047,0046,0043"); params.put("downlimit", "1"); params.put("uplimit", "100"); client.post(url, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { super.onSuccess(statusCode, headers, response); Toast.makeText(getApplication(),"同步數據完成",Toast.LENGTH_SHORT).show(); Toast.makeText(getApplication(), response, Toast.LENGTH_LONG).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { //在主線程中執行 Toast.makeText(getApplication(),"同步數據完成",Toast.LENGTH_SHORT).show(); } }, 500); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); Toast.makeText(getApplication(), "同步數據失敗", Toast.LENGTH_LONG).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { //在主線程中執行 Toast.makeText(getApplication(), "同步數據失敗", Toast.LENGTH_LONG).show(); } }, 50); } });
2. compile 'org.xutils:xutils:3.2.2':
String url = "http://222.169.11.226:7000/WebServiceAndroidcm.asmx/GetCminfoByTzcodeList"; // String url = "http://123.232.120.76:6011/api/UserInfo?xq_id=1"; RequestParams params = new RequestParams(url); params.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8"); params.addBodyParameter("loginer_id", "4363"); params.addBodyParameter("tzcodelist", "0047,0046,0043"); params.addBodyParameter("downlimit", "1"); params.addBodyParameter("uplimit", "100"); x.http().post(params, new Callback.CommonCallback<String>() { @Override public void onCancelled(Callback.CancelledException arg0) { Toast.makeText(getApplication(), "cancle", Toast.LENGTH_SHORT).show(); } // 注意:如果是自己onSuccess回調方法里寫了一些導致程序崩潰的代碼,也會回調道該方法,因此可以用以下方法區分是網絡錯誤還是其他錯誤 // 還有一點,網絡超時也會也報成其他錯誤,還需具體打印出錯誤內容比較容易跟蹤查看 @Override public void onError(Throwable ex, boolean isOnCallback) { Toast.makeText(x.app(), "fuk", Toast.LENGTH_SHORT).show(); if (ex instanceof HttpException) { // 網絡錯誤 HttpException httpEx = (HttpException) ex; int responseCode = httpEx.getCode(); String responseMsg = httpEx.getMessage(); String errorResult = httpEx.getResult(); Toast.makeText(getApplication(), errorResult, Toast.LENGTH_SHORT).show(); // ... } else { // 其他錯誤 // ... Toast.makeText(x.app(), "funck you", Toast.LENGTH_SHORT).show(); } } // 不管成功或者失敗最后都會回調該接口 @Override public void onFinished() { // Toast.makeText(getApplication(), "llafda", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(String arg0) { Toast.makeText(getApplication(), "chegngonng le ", Toast.LENGTH_SHORT).show(); } });
3. 自帶的http:
運用原生Java Api發送簡單的Get請求、Post請求步驟
- 通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection)
- 設置請求的參數
- 發送請求
- 以輸入流的形式獲取返回內容
- 關閉輸入流
package me.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.Iterator; import java.util.Map; public class HttpRequestor { private String charset = "utf-8"; private Integer connectTimeout = null; private Integer socketTimeout = null; private String proxyHost = null; private Integer proxyPort = null; /** * Do GET request * @param url * @return * @throws Exception * @throws IOException */ public String doGet(String url) throws Exception { URL localURL = new URL(url); URLConnection connection = this.openConnection(localURL); HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setRequestProperty("Accept-Charset", charset); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader reader = null; StringBuffer resultBuffer = new StringBuffer(); String tempLine = null; //響應失敗 if (httpURLConnection.getResponseCode() >= 300) { throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode()); } try { inputStream = httpURLConnection.getInputStream(); inputStreamReader = new InputStreamReader(inputStream); reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } } finally { if (reader != null) { reader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } if (inputStream != null) { inputStream.close(); } } return resultBuffer.toString(); } /** * Do POST request * @param url * @param parameterMap * @return * @throws Exception */ public String doPost(String url, Map parameterMap) throws Exception { /* Translate parameter map to parameter date string */ StringBuffer parameterBuffer = new StringBuffer(); if (parameterMap != null) { Iterator iterator = parameterMap.keySet().iterator(); String key = null; String value = null; while (iterator.hasNext()) { key = (String)iterator.next(); if (parameterMap.get(key) != null) { value = (String)parameterMap.get(key); } else { value = ""; } parameterBuffer.append(key).append("=").append(value); if (iterator.hasNext()) { parameterBuffer.append("&"); } } } System.out.println("POST parameter : " + parameterBuffer.toString()); URL localURL = new URL(url); URLConnection connection = this.openConnection(localURL); HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Accept-Charset", charset); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length())); OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader reader = null; StringBuffer resultBuffer = new StringBuffer(); String tempLine = null; try { outputStream = httpURLConnection.getOutputStream(); outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(parameterBuffer.toString()); outputStreamWriter.flush(); //響應失敗 if (httpURLConnection.getResponseCode() >= 300) { throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode()); } //接收響應流 inputStream = httpURLConnection.getInputStream(); inputStreamReader = new InputStreamReader(inputStream); reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } } finally { if (outputStreamWriter != null) { outputStreamWriter.close(); } if (outputStream != null) { outputStream.close(); } if (reader != null) { reader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } if (inputStream != null) { inputStream.close(); } } return resultBuffer.toString(); } private URLConnection openConnection(URL localURL) throws IOException { URLConnection connection; if (proxyHost != null && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); connection = localURL.openConnection(proxy); } else { connection = localURL.openConnection(); } return connection; } /** * Render request according setting * @param request */ private void renderRequest(URLConnection connection) { if (connectTimeout != null) { connection.setConnectTimeout(connectTimeout); } if (socketTimeout != null) { connection.setReadTimeout(socketTimeout); } } /* * Getter & Setter */ public Integer getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } public Integer getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(Integer socketTimeout) { this.socketTimeout = socketTimeout; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } }
異步get(石秦):
new Thread(new Runnable() { String url = "http://123.232.120.76:6011/api/Login?user_name=zll&pwd=1"; Message msg = new Message(); @Override public void run() { try { URL urlString = new URL(url); //打開url HttpURLConnection connection = (HttpURLConnection)urlString.openConnection(); //請求超時 connection.setConnectTimeout(2000); //讀取超時 connection.setReadTimeout(2000); //獲取請求成功響應碼 if (connection.getResponseCode() == 200) { InputStream is = connection.getInputStream(); String json = StreamUtil.streamtoString(is); // json.replace("[", ""); // json.replace("]", ""); Log.d("json", json); System.out.print(json); JSONObject jsonObject = new JSONObject(json); } } catch (MalformedURLException e) { e.printStackTrace(); msg.what = URLERROR; Log.d("url", "aaaa"); } catch (IOException e) { e.printStackTrace(); msg.what = IOERROR; Log.d("io", "qqqqq"); } catch (JSONException e) { e.printStackTrace(); msg.what = JSONERROR; Log.d("jsonfailure", "qqqqq"); } } }).start();