HttpURLConnection, Android访问网络,实用demo
生活随笔
收集整理的這篇文章主要介紹了
HttpURLConnection, Android访问网络,实用demo
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
常量
private static final String CHARSET = "UTF-8";
private static final String HTTP_METHOD_POST = "POST";
private static final String PARAMETER_KEY_REN_CODE = "renCode";
?
1、使用AsyTask訪問(wèn)網(wǎng)絡(luò)
class MyAsyncTask extends AsyncTask<String,Void,String> {@Overrideprotected String doInBackground(String... strings) { // http://61.145.196.120:8080/wangbaApp/appUnitRegister?renCode=114419010199String url = "http://61.145.196.120:8080/wangbaApp/appUnitRegister";Log.i("lgq","ssshhh==onPostExecute====tttt==="+url);List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();pairs.add(new Pair<String, String>(PARAMETER_KEY_REN_CODE, strings[0]));String result = doPost(url, pairs);return result;}@Overrideprotected void onPostExecute(String ss) {super.onPostExecute(ss);//隱藏progressBartry {JSONObject object = new JSONObject(ss); // Log.i("lgq", "re==logtest=====" + s);} catch (JSONException e) {e.printStackTrace();}}}2、工具方法:
public static String doPost(String url, List<Pair<String, String>> params) {return doRequest(url, params, HTTP_METHOD_POST);}private static String doRequest(String url, List<Pair<String, String>> params, String type){ // MLog.d(TAG, "request url : " + url + " method is : " + type);InputStream in = null;try {HttpURLConnection conn = getHttpURLConnection(url);conn.setRequestMethod(type);if(params != null && !params.isEmpty()){setParams(conn, params);}conn.connect();// MLog.d(TAG,"ResponseCode : " + conn.getResponseCode());if(HttpURLConnection.HTTP_OK == conn.getResponseCode() ){in = conn.getInputStream();return readStream(in);}else {return "網(wǎng)絡(luò)連接失敗"+conn.getURL(); // throw new NetWorkException("ResponseCode : " + conn.getResponseCode());}} catch (IOException e) {e.printStackTrace(); // MLog.w(TAG, e.getMessage(), e);return "網(wǎng)絡(luò)連接失敗222"; // throw new NetWorkException("net work fail: " + e);}finally {if(in != null){try {in.close();} catch (IOException e) { // MLog.w(TAG, "io close fail", e);}}}}private static String readStream(InputStream in) throws IOException {char[] buffer = new char[1024];BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET));int len = 0;StringBuilder strBuilder= new StringBuilder();while ((len = reader.read(buffer)) != -1){strBuilder.append(buffer, 0, len);}return strBuilder.toString();}private static HttpURLConnection getHttpURLConnection(String url) throws IOException {URL mUrl = new URL(url);HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();conn.setReadTimeout(10000);conn.setConnectTimeout(15000);conn.setDoInput(true);conn.setDoOutput(true);return conn;}private static void setParams(HttpURLConnection conn, List<Pair<String, String>> params) throws IOException {BufferedWriter writer = null;try {writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), CHARSET));StringBuilder result = new StringBuilder();boolean first = true;for (Pair pair : params){if (first)first = false;elseresult.append("&");result.append(URLEncoder.encode(pair.first.toString(), CHARSET));result.append("=");result.append(URLEncoder.encode(pair.second.toString(), CHARSET));}// MLog.d(TAG,"URL:"+result.toString());writer.write(result.toString());writer.flush();Log.i("Lgq","......"+result.toString());}finally {if(writer != null){try {writer.close();} catch (IOException e) { // MLog.w(TAG, e.getMessage(), e);}}}}?
3、開(kāi)始訪問(wèn)網(wǎng)絡(luò)
new MyAsyncTask().execute("114419010199");?若返回json出現(xiàn)中文亂碼解決方法:https://blog.csdn.net/meixi_android/article/details/87934782
總結(jié)
以上是生活随笔為你收集整理的HttpURLConnection, Android访问网络,实用demo的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 原生js的dom操作
- 下一篇: 元素上下左右居中的几种方法