你没有被骗,你看我的文章,就说明你是爱好学习,天天向上的好人,祝你五一快乐,单身的就加班偷偷打怪升级变成boss。
如果赞超过10,我对地发誓,把我高中从一个棒棒糖开始的初恋故事分享给你们。
讲到我们Android原生的网络请求 在Android 2.2之前用HttpClient是较好的选择;在Android 2.3之后就是用HttpURLConnection。
选择英雄
HttpURLConnection API简单体积小,HttpURLConnection 的压缩和缓存机制可以有效地减少网络访问的流量。在提升速度和省电方面也起到了较大作用。
所以,Android6.0把HttpClient移除了,如果你就想怀恋小时候的青梅竹马,就请引用HttpClient
全军出击
就拿HttpURLConnection的post请求做例子,回到你原生初恋的感觉
先配置我们的HttpURLConnection
public static HttpURLConnection getHttpURLConnection(String url){
HttpURLConnection mHttpURLConnection=null;
try {
URL mUrl=new URL(url);
mHttpURLConnection=(HttpURLConnection)mUrl.openConnection();
//设置连接超过时间
mHttpURLConnection.setConnectTimeout(15000);
//设置读取超过时间
mHttpURLConnection.setReadTimeout(15000);
//添加请求参数
mHttpURLConnection.setRequestMethod("POST");
//添加Header
mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");
//接入输入流
mHttpURLConnection.setDoInput(true);
//传递参数时需要开启
mHttpURLConnection.setDoOutput(true);
} catch (IOException e) {
e.printStackTrace();
}
return mHttpURLConnection;
}
准备团战
把我们的请求参数写入输出流
public static void postParams(OutputStream output,List<NameValuePair>paramsList) throws IOException{
StringBuilder mStringBuilder=new StringBuilder();
for (NameValuePair pair:paramsList){
if (!TextUtils.isEmpty(mStringBuilder)){
mStringBuilder.append("&");
}
mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
mStringBuilder.append("=");
mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
}
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
writer.write(mStringBuilder.toString());
writer.flush();
writer.close();
}
技能锁定
给个地址和我们的post参数
private void useHttpUrlConnectionPost(String url){
InputStream mInputStrea=null;
HttpURLConnection mHttpURLConnection=getHttpURLConnection(url);
try {
List<NameValuePair> postParams=new ArrayList<>();
postParams.add(new BasicNameValuePair("ip","59.108.54.37"));
postParams(mHttpURLConnection.getOutputStream(),postParams);
mHttpURLConnection.connect();
mInputStrea=mHttpURLConnection.getInputStream();
int code=mHttpURLConnection.getResponseCode();
String respose=converStreamToString(mInputStrea);
Log.d(TAG, "请求状态码:"+code+"\n请求结果\n"+respose);
mInputStrea.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Victory
在看看我们的活动中的调用
new Thread(new Runnable() {
@Override
public void run() {
useHttpUrlConnectionPost("http://ip.taobao.com/service/getIpInfo.php");
}
}).start();
小小提醒啊,地址我照书上打的,有问题你就换个天气的地址访问,不知道给你个
和风天气接口地址
下期见