Android主要就是HTTP请求
主要使用原生的HttpURLConnection或者开源框架okhttp3和retrofit2
HttpURLConnection示例get请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader=null;
try{
URL url=new URL("https://www.baidu.com");
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
builder.append(line);
}
Log.i(TAG, "onCreate: "+builder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
HttpURLConnection示例post请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader=null;
try{
URL url=new URL("https://www.baidu.com");
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoOutput(true);
OutputStream outputStream=connection.getOutputStream();
String s="telephone=17131454890";
byte[] b=s.getBytes();
outputStream.write(b);
outputStream.close();
InputStream in=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(in));
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null){
builder.append(line);
}
Log.i(TAG, "onCreate: "+builder.toString());
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
}
}).start();
okhttp3请看我的另一篇博客:
https://blog.youkuaiyun.com/yh18668197127/article/details/85065288
retrofit2请看我的另一篇博客
https://blog.youkuaiyun.com/yh18668197127/article/details/85064994