首先网络请求不能放于主线程,必须开启子线程操作
public static final String dataUrl = "http://guolin.tech/api/china";
Get请求:
private void getData(){ URL url; BufferedReader bufferedReader = null; HttpURLConnection connection = null; try { url = new URL(Config.dataUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setRequestMethod("GET"); InputStream inputStream = connection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuffer = new StringBuilder(); String line; while((line = bufferedReader.readLine())!=null){ stringBuffer.append(line); } LogUtils.e("获取到的内容"+stringBuffer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } if(bufferedReader!=null){ try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Post请求:
private void myPost(){ URL url; BufferedReader bufferedReader = null; HttpURLConnection connection = null; try { url = new URL(Config.dataUrl); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setReadTimeout(10000); connection.setConnectTimeout(10000); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes("username=admin&password=123456"); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while((line = reader.readLine())!=null){ stringBuilder.append(line); } LogUtils.e("打印Post内容"+stringBuilder.toString()); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } if(bufferedReader!=null){ try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }