Android第一次项目
学习了一个月的Android,接触了人生中第一个安卓项目,对于一个小白来说,总结是很重要的学习方法,以下我把学到的东西总结以下:
1. 1》okhttp3用法解析(边贴代码边熟悉)
public class OkhttpService {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); //json请求
public static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
private static OkhttpService instance;
private OkHttpClient client;
private OkhttpService() {
client = new OkHttpClient(); //获取OkthhpClient实例
}
public static OkhttpService getInstance() {
return instance == null ? instance = new OkhttpService() : instance;
}
//魔盒批量封装 (post提交json数据)
注:RequestBody body = RequestBody.create(JSON, json); //json数据为body
Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。
public String insertBoxProd(List<BoxProdInfo> boxProd)throws IOException{
HttpUrl route = HttpUrl.parse("http://115.29.165.110:8085/RfService.svc/V1.0/Mh/InsertBoxProd/");
String json = new Gson().toJson(boxProd); //将boxProd序列化为json
Request request = new Request.Builder()
.url(route)
.post(RequestBody.create(JSON, json)) //使用Request的post方法来提交请求体RequestBody
.build();
Response response = client.newCall(request).execute();
boolean isOk=response.isSuccessful();
return response.body().string(); //response.body()返回ResponseBody类
}
//网点提交盒子收货上架
public String receiverBox(String userCode, List<BoxReceiverInfo> boxReceiverInfos)throws IOException{
HttpUrl route=HttpUrl.parse("http://115.29.165.110:8085/RfService.svc/V1.0/Mh/ReceiveBox/")
.newBuilder()
.addPathSegment(userCode)
.build();
String json=new Gson().toJson(boxReceiverInfos);
Request request=new Request.Builder()
.url(route)
.put(RequestBody.create(JSON,json))
.build();
Response response=client.newCall(request).execute();
boolean isOk=response.isSuccessful();
return response.body().string();
}
}
注:以上两个方法需要在前台访问。且需要返回结果提示给前台(接口中需提供 States(返回状态:成功或失败),Description(结果描述),Data(数据)等)
eg:String result = OkhttpService.getInstance().receiverBox(userCode,boxReceiverInfos).toString();
2》官方文档总结
(1)配置
导入Jar包
通过构建方式导入=== meaven (2)基本要求
Request请求
Response响应 (3)基本使用
《--》Http GET okHtttpClient client=new okHtttpClient(); String run(String url)throws IOException{
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}else{
throw new IOException("Unexpected code " + response);
}
}
注:Request是OkHttp中访问的请求,Builder是辅助类,Response即OkHttp中的响应 《--》Http POST 》》》POST提交Json数据 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful())
{
return response.body().string();
} else
{
throw new IOException("Unexpected code " + response);
}
}
注:使用Request的post方法来提交请求体RequestBody 》》》POST提交键值对
OkHttp也可以通过POST方式把键值对数据传送到服务器 OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build(); Request request = new Request.Builder()
.url(url)
.post(body)
.build(); Response response = client.newCall(request).execute();
if (response.isSuccessful())
{
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
(3)案例 布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button android:id="@+id/bt_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="乌云Get请求"/> <Button android:id="@+id/bt_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="乌云Post请求"/> LinearLayout> <TextView android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> LinearLayout> Java代码:
由于android本身是不允许在UI线程做网络请求操作的,所以我们自己写个线程完成网络操作 import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button bt_get;
private Button bt_post;
final OkHttpClient client = new OkHttpClient(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bt_get=(Button)findViewById(R.id.bt_get);
bt_post=(Button)findViewById(R.id.bt_post);
bt_get.setOnClickListener(this);
bt_post.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bt_get:
getRequest();
break; case R.id.bt_post:
postRequest();
break;
}
}
private void getRequest() {
final Request request=new Request.Builder()
.get()
.tag(this)
.url("http://www.wooyun.org")
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","打印GET响应的数据:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} private void postRequest() {
RequestBody formBody = new FormEncodingBuilder()
.add("","")
.build();
final Request request = new Request.Builder()
.url("http://www.wooyun.org")
.post(formBody)
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","打印POST响应的数据:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} 剩下的简单说明:
同步Get
下载一个文件,打印他的响应头,以string形式打印响应体。
响应体的 string() 方法对于小文档来说十分方便、高效。但是如果响应体太大(超过1MB),应避免适应 string()方法 ,因为他会将把整个文档加载到内存中。对于超过1MB的响应 body,应使用流的方式来处理body。

异步Get
在一个工作线程中下载文件,当响应可读时回调Callback接口。读取响应时会阻塞当前线程。OkHttp现阶段不提供异步api来接收响应体。

提取响应头
典型的HTTP头 像是一个 Map

Post方式提交String
使用HTTP POST提交请求到服务。这个例子提交了一个markdown文档到web服务,以HTML方式渲染markdown。因为整个请求体都在内存中,因此避免使用此api提交大文 档 (大于1MB)。
待续。。。。。。。。。
部分出自 http://m.2cto.com/net/201605/505364.html
Android第一次项目的更多相关文章
- fir.im Weekly - 从零开始创建 Android 新项目
今年的 Google I/O 大会上,人工智能和虚拟现实的产品发布让我们对未来多了几分惊喜.对于开发者部分,Google 发布了 Android N 系统,感受最深的是全新的 Android Stud ...
- 【Android 应用开发】GitHub 优秀的 Android 开源项目
原文地址为http://www.trinea.cn/android/android-open-source-projects-view/,作者Trinea 主要介绍那些不错个性化的View,包括Lis ...
- Android 开源项目及其学习
Android 系统研究:http://blog.csdn.net/luoshengyang/article/details/8923485 Android 腾讯技术人员博客 http://hukai ...
- 关于Android多项目依赖在Eclipse中无法关联源代码的问题解决
被Eclipse中Android依赖项目无法关联源代码的问题困扰了许久,网上搜索了一下,终于得到解决,大大提高了开发效率. 问题描述: 项目有A,B两个Android Project组成, B是And ...
- Android studio 使用Gradle发布Android开源项目到JCenter 总结
1.注册账号 先到https://bintray.com注册一个账号. 这个网站支持 github 账户直接登录的 2.获取 bintray.user 和 bintray.apikey ...
- [转]Android开源项目第二篇——工具库篇
本文为那些不错的Android开源项目第二篇--开发工具库篇,主要介绍常用的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多 ...
- 2015-2016最火的Android开源项目--github开源项目集锦(不看你就out了)
标签: Android开发开源项目最火Android项目github 2015-2016最火的Android开源项目 本文整理与集结了近期github上使用最广泛最火热与最流行的开源项目,想要充电与提 ...
- Android开源项目分类汇总
目前包括: Android开源项目第一篇——个性化控件(View)篇 包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView. ...
- fir.im Weekly - 1000 个 Android 开源项目集合
冬天到了,适宜囤点代码暖暖身.本期 fir.im Weekly 收集了最近一些不错的 GitHub 源码.开发工具和技术实践教程类文章分享给大家. codeKK - 集合近 1000 Android ...
随机推荐
- enote笔记语言(4)
what:我想知道某个“关键词(keyword)”(即,词语,可以是概念|专业术语|.......)的定义. why:我想知道事物发生的原因:我会不会犯“归因错误”?是“单因素”的还是“多因素”的原因 ...
- Nginx配置文件的高亮显示设置
linux系统下vim或者vi编辑器默认是没有对nginx的语法高亮设置. 1.下载vi语法高亮配置到 ~/.vim/syntax,如果不存在则创建该目录,cd ~/.vim/syntax wget ...
- 爬虫系列(三) urllib的基本使用
一.urllib 简介 urllib 是 Python3 中自带的 HTTP 请求库,无需复杂的安装过程即可正常使用,十分适合爬虫入门 urllib 中包含四个模块,分别是 request:请求处理模 ...
- 【Codeforces 1114A】Got Any Grapes?
[链接] 我是链接,点我呀:) [题意] 水题 [题解] 哪个比较挑剔优先给他选>_< [代码] import java.io.*; import java.util.*; public ...
- poj 2553强连通+缩点
/*先吐槽下,刚开始没看懂题,以为只能是一个连通图0T0 题意:给你一个有向图,求G图中从v可达的所有点w,也都可以达到v,这样的v称为sink.求这样的v. 解;求强连通+缩点.求所有出度为0的点即 ...
- [bzoj1103][POI2007]大都市meg_dfs序_树状数组
大都市meg bzoj-1103 POI-2007 题目大意:给定一颗n个点的树,m次操作.将一条路的边权更改成0:查询一个点到根节点的点权和.开始的时候所有边的边权都是1. 注释:$1\le n,m ...
- propagation属性的7个传播行为
关于propagation属性的7个传播行为 REQUIRED:指定当前方法必需在事务环境中运行,如果当前有事务环境就加入当前正在执行的事务环境,如果当前没有事务,就新建一个事务.这是默认值.即有事务 ...
- 开源GIS软件 4
空间数据操作框架 Apache SIS Apache SIS 是一个空间的框架,可以更好地搜索,数据聚类,归档,或任何其他相关的空间坐标表示的需要. kvwmap kvwmap是一个采用PHP开发的W ...
- portmap 和 rpc程序
Portmap 是为RPC 程序服务的. 每一个RPC server程序启动的时候要向portmap程序注册.这样portmap程序就知道这些RPC server监听在哪个端口. 而RPC clien ...
- hdu5242 上海邀请赛 优先队列+贪心
题意是给你一棵树 n个点 n-1条边 起点是1 每一个点都有权值 每次能从根节点走到叶子节点 经行k次游戏 每次都是从1開始 拿过的点的权值不能拿第二次 问最大权值和. 開 ...