Android 网络编程实例

news/2025/1/15 18:12:05/

一、前端

  •       网络请求库: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"><ImageViewandroid:id="@+id/siv_icon"android:layout_width="80dp"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:layout_marginBottom="5dp"/><TextViewandroid: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="我是标题"/><TextViewandroid: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="我是描述"/><TextViewandroid: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>();@Overrideprotected 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() {@Overridepublic void onFailure(Call call, IOException e) {Log.i("onfail",e.getMessage());}@Overridepublic 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() {@Overridepublic 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{@Overridepublic int getCount(){return  newsInfos.size();}@Overridepublic 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;}@Overridepublic  Object getItem(int position){return newsInfos.get(position);}@Overridepublic  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 mapperPUBLIC "-//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 {@Autowiredprivate 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>

三、运行结果


http://www.ppmy.cn/news/118449.html

相关文章

android 7.1 壁纸路径,android 7.1 默认动态壁纸

最近客户提了个需求&#xff1a;升级后默认使用动态壁纸。 但是根据网络资料大量修改动态壁纸的都是修改frameworks/base/core/res/res/values/config.xml文件中 default_wallpaper_component就好了。 我尝试改了一下&#xff0c;升级后第一次开机变现为纯黑色壁纸&#xff0c;…

android高清壁纸,40张极Cool的Android系统桌面壁纸

40张极Cool的Android系统桌面壁纸 1月 3, 2013 评论 (15) Sponsor 现在很多用户使用了Andriod系统的智能手机,但作为设计师是不是应该要换一下系统桌面壁纸呢,今天为你分享一些设计感不错的安卓系统桌面壁纸,我想这些Android壁纸除了酷和漂亮外,还能给我们一些创造灵感,你…

Python numpy - 数组的创建与访问

目录 概要 数组array的创建 1 用 list 创建 2 通过list创建二维数组 3 函数arange创建 等差数组 4 函数zeros创建 零矩阵 5 函数eyes创建 单位矩阵 6 随机函数创建 数组array的访问 1 访问形状/元素个数/数据类型 2 访问一维数组的位置/范围 3 访问二维数组的位置/范…

Android常用的网络权限,Android常用的权限大全

Android的常用权限 访问网络 android.permission.INTERNET 访问网络连接可能产生GPRS流量 写入外部存储 android.permission.WRITE_EXTERNAL_STORAGE 允许程序写入外部存储&#xff0c;如SD卡上写文件 获取网络状态 android.permission.ACCESS_NETWORK_STATE 获取网络信息状态&…

android 动态壁纸 时钟,Android动态时钟壁纸开发

本文实例为大家分享了Android动态时钟壁纸展示的具体代码&#xff0c;供大家参考&#xff0c;具体内容如下 先看效果 上图是动态壁纸钟的一个时钟。 我们先来看看 Livewallpaper(即动态墙纸)的实现&#xff0c;Android的动态墙纸并不是GIF图片&#xff0c;而是一个标准的Androi…

android中网格布局背景图片,android 网格显示问题

按照教程进行操作 不知道显示怎么成这样的效果 上下两行的间隔太大 而且文字和图片之间的间隔也很大 布局文件也进行了修改 还是不行 有遇到过类似问题的人么 希望您给我一点意见 mainactivity.java package com.example.imageview; import java.util.ArrayList; import java.u…

Android设置来电壁纸,来电壁纸秀下载-来电壁纸秀 安卓版v1.0.7-PC6安卓网

来电壁纸秀是一款特别炫酷的来电壁纸美化软件。来电壁纸秀app给大家准备了超级多的精美壁纸素材&#xff0c;来电壁纸秀不仅有无数的壁纸素材&#xff0c;而且来电壁纸秀app还有很多来电秀模板&#xff01; 软件介绍 来电壁纸秀是一款来电秀主题设置应用。来电壁纸秀app:为大家…

android 设置系统壁纸,Android HttpURLConnection下载网络图片设置系统壁纸

需求&#xff1a; 壁纸是url链接&#xff0c;get就能请求到&#xff0c;所以就用get请求到图片&#xff0c;把图片转化为bitmap&#xff0c;然后设置壁纸。 代码&#xff1a; 这里我封装了工具类 package xxxxx.utils; import android.app.Activity; import android.app.Wallpa…