Android 网络编程实例
一、前端网络请求库:okHttp3 版本3.10.0https://blog.csdn.net/kangguang/article/details/104031756图片加载库:GlideannotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'...
·
一、前端
- 网络请求库:okHttp3 版本3.10.0 https://blog.csdn.net/kangguang/article/details/104031756
- 图片加载库:Glide
annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'
implementation 'jp.wasabeef:glide-transformations:2.0.2' i
mplementation 'com.squareup.okhttp3:okhttp:3.10.0'
- Json解析:Fastjson 版本 com.alibaba:fastjson:1.2.41
- 采用组件ListView 并在Adapter 中做了缓存优化
- 数据返回处理数据bean 中的属性字段没有和后台一致,手动赋值处理
- Activity:NetworkActivity
- Adapter item:new_item.xml
- 网络请求错误处理 https://blog.csdn.net/kangguang/article/details/104031756
代码如下:
1.new_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="65dp">
<ImageView
android:id="@+id/siv_icon"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_title"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@id/siv_icon"
android:ellipsize="end"
android:maxLength="20"
android:singleLine="true"
android:textColor="#990000"
android:textSize="18sp"
android:text="我是标题"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_description"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@id/siv_icon"
android:layout_below="@id/tv_title"
android:ellipsize="end"
android:maxLength="16"
android:singleLine="true"
android:textColor="#990000"
android:textSize="14sp"
android:text="我是描述"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_type"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:textColor="#990000"
android:textSize="12sp"
android:text="评论"
/>
</RelativeLayout>
2.NetworkActivity
public class NetworkActivity extends AppCompatActivity {
private LinearLayout loading;
private ListView lvNews;
private ArrayList<NewsInfo> newsInfos = new ArrayList<NewsInfo>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
initView();
fillData();
}
private void initView()
{
loading = (LinearLayout) findViewById(R.id.loading);
lvNews = (ListView)findViewById(R.id.lv_news);
}
private void fillData()
{
String url =getString(R.string.serverurl);
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
final Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onfail",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try(ResponseBody responseBody = response.body()) {
if (!response.isSuccessful())throw new IOException(("unexpected code"+response));
final String mstring = responseBody.string();
final Runnable runnable = new Runnable() {
@Override
public void run() {
try {
dataProcessing(mstring);
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(){
public void run(){
new Handler(Looper.getMainLooper()).post(runnable);
}
}.start();
}
}
});
}
private void dataProcessing(String jsonstr) throws Exception {
JSONObject jsonObject = JSONObject.parseObject(jsonstr);;
int reslut = jsonObject.getInteger("result");
if ( reslut!= 1 )
{
Toast.makeText(NetworkActivity.this,jsonObject.getString("msg"),Toast.LENGTH_SHORT).show();
return;
}
List<Map<String, Object>> list = JSON.parseObject(String.valueOf(jsonObject.get("data")), List.class);
if (list.size()>0)
{
for (int i = 0;i<list.size();i++)
{
NewsInfo newsInfo = new NewsInfo();
Map<String, Object> mapList = list.get(i);
for(Map.Entry<String, Object> entry : mapList.entrySet()){
String mapKey = entry.getKey();
String mapValue = (String) entry.getValue();
switch (mapKey){
case "news_title":
newsInfo.setTitle(mapValue);
break;
case "news_icon_path":
newsInfo.setIcon(mapValue);
break;
case "news_content":
newsInfo.setContent(mapValue);
break;
case "news_Comment":
newsInfo.setComment(mapValue);
break;
case "news_Type":
newsInfo.setType(mapValue);
break;
default:
break;
}
}
newsInfos.add(newsInfo);
}
loading.setVisibility(View.INVISIBLE);
lvNews.setAdapter(new NewsAdapter());
}
else
{
Toast.makeText(NetworkActivity.this, "没有新闻",Toast.LENGTH_SHORT).show();
}
}
private class NewsAdapter extends BaseAdapter{
@Override
public int getCount()
{
return newsInfos.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
convertView= LayoutInflater.from(NetworkActivity.this).inflate(R.layout.new_item,parent,false);
holder = new ViewHolder();
holder.siv = (ImageView)convertView.findViewById(R.id.siv_icon);
holder.tv_title = (TextView)convertView.findViewById(R.id.tv_title);
holder.tv_description = (TextView)convertView.findViewById(R.id.tv_description);
holder.tv_type = (TextView)convertView.findViewById(R.id.tv_type);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
NewsInfo newsInfo = newsInfos.get(position);
Glide.with(NetworkActivity.this).load( "http://192.168.0.102:8080/myssm"+newsInfo.getIcon()).into(holder.siv);
holder.tv_title.setText(newsInfo.getTitle());
holder.tv_description.setText(newsInfo.getContent());
switch (newsInfo.getType())
{
case "1":
holder.tv_type.setText("评论:"+ newsInfo.getType());
break;
case "2":
holder.tv_type.setText("专题:"+newsInfo.getType());
break;
case "3":
holder.tv_type.setTextColor(Color.BLUE);
holder.tv_type.setText("LIVE");
break;
default:
break;
}
return convertView;
}
@Override
public Object getItem(int position)
{
return newsInfos.get(position);
}
@Override
public long getItemId(int positon)
{
return positon;
}
class ViewHolder{
private TextView tv_title;
private TextView tv_description;
private TextView tv_type;
private NewsInfo newsInfo;
private ImageView siv;
}
}
}
二、后台
- 框架SSM
- 数据库:mysqol
- fileUpload.jsp页面负责上传新闻信息
- FileUploadController 负责文件上传处理和请求响应
- Bean:NewsInfo
- Dao:NewsInfoDao接口负责查询 NewsInfo.xml负责插入
- Service:NewsInfoService接口 NewsInfoServiceImpl服务处理
代码如下:
1.FileUploadController
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("title") String title,
@RequestParam("content") String content,
@RequestParam("type") int type,
@RequestParam("comment") int comment,
@RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request)
{
if(!uploadfile.isEmpty() && uploadfile.size() >0)
{
String dirpath = request.getServletContext().getRealPath("/images/");
String newFilename = new String();
for(MultipartFile file : uploadfile)
{
String originaFileName = file.getOriginalFilename();
File filepath = new File(dirpath);
if(!filepath.exists())
{
filepath.mkdirs();
}
newFilename = name + "_"+ UUID.randomUUID()+"_"+originaFileName;
System.out.println(dirpath);
try {
file.transferTo(new File(dirpath+newFilename));
}catch (Exception e)
{
e.printStackTrace();
return "error";
}
}
NewsInfo news = new NewsInfo();
news.setNews_title(title);
news.setNews_type(String.valueOf(type));
news.setNews_comment(String.valueOf(comment));
news.setNews_icon_path("/images/" + newFilename);
news.setNews_content(content);
newsInfoService.addnews(news);
return "success";
}else {
return "error";
}
}
@RequestMapping(value = "/findnews")
@ResponseBody
public void findnews(HttpServletResponse response) throws ServletException, IOException
{
response.setHeader("Content-Type","text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Map map = new HashMap();
map.put("result","1");
map.put("msg","执行成功");
List<NewsInfo> list = newsInfoService.findNews();
map.put("data",list);
String json = JSONObject.toJSON(map).toString();
out.write(json);
out.close();
}
2.NewsInfo.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace 表示命名空间 --> <mapper namespace="com.kangxg.dao.NewsInfoDao"> <insert id="addnews" parameterType = "NewsInfo" > insert into t_newsinfo( news_title, news_icon_path, news_type, news_content, news_comment ) values ( #{news_title}, #{news_icon_path}, #{news_type}, #{news_content}, #{news_comment} ) </insert> </mapper>
3.NewsInfoDao
@Select("select * from t_newsinfo")
public List<NewsInfo> findNews();
4.NewsInfoServiceImpl
@Service
@Transactional
public class NewsInfoServiceImpl implements NewsInfoService {
@Autowired
private NewsInfoDao newsInfoDao;
public void addnews(NewsInfo newsInfo){
newsInfoDao.addnews(newsInfo);
}
public List<NewsInfo> findNews()
{
return newsInfoDao.findNews();
}
}
5. fileUpload.jsp
<html>
<head>
<title>文件上传</title>
<script>
function check() {
var name = document.getElementById("name").value;
var file = document.getElementById("file".value);
if(name == "")
{
alert("填写上传人")
return false;
}
if(file.length == 0 || file =="")
{
alert("请选择上传文件")
return false;
}
return false;
}
</script>
</head>
<body>
<span>安卓新闻测试文件上传</span>
<form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data" onsubmit="return check()">
上传人:<input type="text" id = "name" name="name"><br>
标题: <input type="text" id = "title" name="title"><br>
描述:<input type="text" id = "content" name="content"><br>
类型:<input type="text" id = "type" name="type"><br>
评论数:<input type="text" id = "comment" name="comment"><br>
请选择文件:<input type="file" id = "file" name="uploadfile" multiple="multiple"><br/>
<input type="submit" value="上传">
</form>
<a href="${pageContext.request.contextPath}/download?filename=<%= URLEncoder.encode("背景壁纸.png","UTF-8")%>">
中文名称文件下载
</a>
<br/>
<a href="${pageContext.request.contextPath}/findnews">
获取json数据
</a>
</body>
</html>
三、运行结果
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)