android发送http请求注意事项

注意事项

1、用户权限需要添加android.permission.INTERNET
2、不能在主线程上发送http请求,因为主线程是UI控制线程

manifests配置权限

<manifest>
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

子线程代码

@Override
public void onClick(View view) {
	new Thread() {
		public void run() {
			try {
				URL url = new URL("https://www.baidu.com");
				HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
				httpURLConnection.setRequestMethod("GET");
				httpURLConnection.setDoInput(true);
				httpURLConnection.setDoOutput(false);
				httpURLConnection.setConnectTimeout(30000);
				httpURLConnection.setReadTimeout(30000);
				httpURLConnection.connect();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
				String line;
				StringBuilder stringBuilder = new StringBuilder();
				String response;
				while ((line = bufferedReader.readLine()) != null) {
					stringBuilder.append(line);
				}
				response = stringBuilder.toString();
				bufferedReader.close();
				httpURLConnection.disconnect();
		   } catch (Exception e) {
			   e.printStackTrace();
		   }
		}
	}.start();
}
...