1.网络配置
在res/xml
新建network_security_config
<network-security-config>
<base-config cleartextTrafficPermitted="true"/>
</network-security-config>
在Manifeste
android:networkSecurityConfig="@xml/network_security_config"
<uses-permission android:name="android.permission.INTERNET"/>
2.get请求
网络请求必须新开一个线程
new Thread() {
@Override
public void run() {
super.run();
get();
}
}.start();
private void get() {
try {
URL url = new URL("http://class.imooc.com/sc/60/learn");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
int len = 0;
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read()) > -1) {
baos.write(b, 0, len);
}
String str = new String(baos.toByteArray());
Log.e("***********************", str);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3.POST请求
private void post() {
try {
URL url = new URL("http://www.imooc.com/api/okhttp/postmethod");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(6000);
conn.setDoOutput(true);
//根据网站自己设置
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream os = conn.getOutputStream();
os.write(("account=111&pwd=111").getBytes());
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
int len = 0;
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = conn.getInputStream();
while ((len = in.read(b)) > -1) {
baos.write(b, 0, len);
}
String str = new String(baos.toByteArray());
Log.e("**************", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}