-
android端获取Tomcat服务器端json数据并通过listview显示
2019-09-26 21:32:50大体意思是用eclipse ee创建一个Javaweb项目,该项目能从MySQL数据库中获取user表的数据,将数据封装成json格式,将此项目发布到本地Tomcat服务器,在android端获取刚才的json数据,并用listview显示。废话不多说下面...大体描述:
大体意思是用eclipse ee创建一个Javaweb项目,该项目能从MySQL数据库中获取user表的数据,将数据封装成json格式,将此项目发布到本地Tomcat服务器,在android端获取刚才的json数据,并用listview显示。废话不多说下面直接开始。
Tomcat服务器端
很简单,建立一个servlet用来处理数据,再建一个数据库工具类,我这里是DatabaseUtil.java,不要忘记servlet在web.xml中需要注册。
项目结构:
code:
ServletDemo1.java
package com.servlet.demo; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import util.DatabaseUtil; public class ServletDemo1 extends HttpServlet { private static final long serialVersionUID = 1L; public ServletDemo1() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sql = "select * from user"; JSONArray jsonArray=new JSONArray(); //json数组 try { ResultSet result = DatabaseUtil.query(sql); while (result.next()) { JSONObject jObject=new JSONObject(); //json临时对象 jObject.put("id", result.getInt(1)); jObject.put("username", result.getString(2)); jObject.put("password", result.getString(3)); jsonArray.add(jObject); //将封装好的json对象放入json数组 } } catch (SQLException e) { e.printStackTrace(); } String jsondata=jsonArray.toString(); //将json数组转换成字符串,供下面返回给android端使用 //System.out.println(jsondata); //本地测试用 response.getWriter().append(jsondata).flush(); } }
DatabaseUtil.java
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Statement; public class DatabaseUtil { private static Connection mConnection; private static Connection getConnection() { if (mConnection == null) { String url = "jdbc:mysql://localhost:3306/mybatis"; try { Class.forName("com.mysql.jdbc.Driver"); mConnection = (Connection) DriverManager.getConnection(url, "root", "123"); } catch (Exception e) { e.printStackTrace(); } } return mConnection; } //这里只用了查询操作 public static ResultSet query(String querySql) throws SQLException { Statement stateMent = (Statement) getConnection().createStatement(); return stateMent.executeQuery(querySql); } public static void closeConnection() { if (mConnection != null) { try { mConnection.close(); mConnection = null; } catch (SQLException e) { e.printStackTrace(); } } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>ConnectTest</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>ServletDemo1</servlet-name> <servlet-class>com.servlet.demo.ServletDemo1</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletDemo1</servlet-name> <url-pattern>/ServletDemo1</url-pattern> </servlet-mapping> </web-app>
本地测试结果
在浏览器地址栏里输入(端口啥的自己改了的话用自己的,不多说)
http://localhost:8080/ConnectTest/ServletDemo1
测试结果:
android端
也比较简单,有两个activity,在mainactivity中有个button按钮,点击后跳转到第二个activity,我这里是ListActivity ,在listactivity中显示获取到的json数据。
用到的jar包
类
布局
code
工具类 HttpUtil
package util; import okhttp3.OkHttpClient; import okhttp3.Request; public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
实体类 User
package com.ccc.connecttest.activity; public class User { private int id; private String username; private String password; public User(int id,String username, String password){ this.id=id; this.username=username; this.password=password; } public int getId() { return id; } public String getUsername() { return username; } public String getPassword() { return password; } }
适配器 UserAdapter
package com.ccc.connecttest.activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.ccc.connecttest.R; import java.util.List; public class UserAdapter extends ArrayAdapter<User> { private int resourceId; public UserAdapter(Context context, int resourceId, List<User> objects) { super(context, resourceId,objects); this.resourceId=resourceId; } @Override public View getView(int position, View convertView,ViewGroup parent) { User user=getItem(position); View view; ViewHolder viewHolder; if(convertView==null){ view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false); viewHolder=new ViewHolder(); viewHolder.userid=(TextView)view.findViewById(R.id.tv_id); viewHolder.username=(TextView)view.findViewById(R.id.tv_username); viewHolder.userpassword=(TextView)view.findViewById(R.id.tv_password); view.setTag(viewHolder); //将viewHolder存储在view中 }else{ view=convertView; viewHolder=(ViewHolder)view.getTag(); } viewHolder.userid.setText(String.valueOf(user.getId())); viewHolder.username.setText(user.getUsername()); viewHolder.userpassword.setText(user.getPassword()); return view; } static class ViewHolder{ TextView userid; TextView username; TextView userpassword; } }
显示的页面 ListActivity
package com.ccc.connecttest.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListView; import com.ccc.connecttest.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import util.HttpUtil; public class ListActivity extends AppCompatActivity { private List<User> userList=new ArrayList<>(); private ListView listView; private String json_url="http://192.168.2.133:8080/ConnectTest/ServletDemo1";//本地Tomcat刚才测试的地址 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); queryFromServer(json_url); //处理取得数据 listView=findViewById(R.id.lv); UserAdapter adapter = new UserAdapter(ListActivity.this, R.layout.user, userList); listView.setAdapter(adapter); } private void queryFromServer(String json_url) { HttpUtil.sendOkHttpRequest(json_url, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.i("error","出现错误!"); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText=response.body().string(); try { JSONArray jsonArray=new JSONArray(responseText); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject=jsonArray.getJSONObject(i); String id=jsonObject.getString("id"); String username=jsonObject.getString("username"); String password=jsonObject.getString("password"); User user=new User(Integer.parseInt(id),username,password); userList.add(user); Log.i("user","添加了一个User"); } } catch (JSONException e) { e.printStackTrace(); } } }); } }
主页面 MainActivity
package com.ccc.connecttest.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.ccc.connecttest.R; public class MainActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=findViewById(R.id.btnSign); //点击跳转到显示页面 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ListActivity.class)); } }); } }
配置 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ccc.connecttest"> <!-- 千万不要忘了申请使用网络权限--> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".activity.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 这个ListActivity不要忘记注册--> <activity android:name=".activity.ListActivity"/> </application> </manifest>
布局
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_marginTop="200dp" android:id="@+id/btnSign" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="获取" /> </LinearLayout
activity_list.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
listview每一项适配文件: user.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="match_parent" android:padding="15dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tv_id" android:text="1111" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" /> <TextView android:text="2222" android:id="@+id/tv_username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" /> <TextView android:text="3333" android:id="@+id/tv_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#d97e87" android:textSize="16sp" /> </LinearLayout> </RelativeLayout>
结果图
附上源码
新demo 用retrofit实现的 上面那个很久以前做的没注意 有问题
new demo
https://github.com/Commandercc/smallthings/blob/master/GetJsonDemo.zip 这个新的demo可以看一下 -
自己搭建tomcat服务器生成json数据,并用android客户端获取
2018-05-21 15:17:59服务端index.jsp: ; charset=UTF-8" pageEncoding="UTF-8"%> <!... ; charset=UTF-8"> <title>Insert title here ... <p> json test ...<%@ taglib prefix="json" uri=...//通过out.Stream.toByteArray获取到写的数据 } }服务端index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <p> json test </p> <%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %> <json:object> <json:property name="itemCount" value="100"/> <json:property name="subtotal" value="$15.50"/> <json:array name="items" var="item" items="1"> <json:object> <json:property name="title" value="The big book of foo"/> <json:property name="description" value="it does not work"/> <json:property name="imageUrl" value="http://www.baidu.com"/> <json:property name="price" value="$100"/> <json:property name="qty" value="1"/> </json:object> <json:object> <json:property name="title" value="The big book of foo2"/> <json:property name="description" value="it does not work2"/> <json:property name="imageUrl" value="http://www.baidu.com2"/> <json:property name="price" value="$1002"/> <json:property name="qty" value="12"/> </json:object> </json:array> </json:object> </body> </html>
服务端生成的json:
{"itemCount":"100","subtotal":"$15.50","items":[{"title":"The big book of foo","description":"it does not work","imageUrl":"http://www.baidu.com","price":"$100","qty":"1"},{"title":"The big book of foo2","description":"it does not work2","imageUrl":"http://www.baidu.com2","price":"$1002","qty":"12"}]}
android端解析代码:
package com.excellence.exampleapp; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class ParseJsonActivity extends Activity { private TextView textView = null; private StringBuilder sb = new StringBuilder(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_parse_json); textView = findViewById(R.id.text); new Thread(new Runnable() { @Override public void run() { try { final String jsonString = readParse("http://10.1.1.155:8080/JsonToAndroid/index.json"); JSONObject object = new JSONObject(jsonString); String itemCount = object.getString("itemCount"); sb.append("\n"+"itemcount : "+itemCount+"\n"); Log.d("jxdJson","itemcount : "+itemCount); String subtotal = object.getString("subtotal"); sb.append("subtotal : "+subtotal+"\n"); Log.d("jxdJson","subtotal : "+subtotal); JSONArray jsonArray = object.getJSONArray("items"); Log.d("jxdJson","jsonArray length : "+jsonArray.length()); for(int i = 0; i<jsonArray.length();i++){ JSONObject arrayObject = jsonArray.getJSONObject(i); String title = arrayObject.getString("title"); Log.d("jxdJson","title : "+title); sb.append("\n"+"title : "+title+"\n"); String description = arrayObject.getString("description"); Log.d("jxdJson","description : "+description); sb.append("\n"+"description : "+description+"\n"); String imageUrl = arrayObject.getString("imageUrl"); Log.d("imageUrl","imageUrl : "+imageUrl); sb.append("\n"+"imageUrl : "+imageUrl+"\n"); String price = arrayObject.getString("price"); Log.d("jxdJson","price : "+price); sb.append("\n"+"price : "+price+"\n"); String qty = arrayObject.getString("qty"); Log.d("jxdJson","qty : "+qty); sb.append("\n"+"qty : "+qty+"\n"); } runOnUiThread(new Runnable() { @Override public void run() { textView.setText(jsonString); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * 从指定的URL中获取数组 * @param urlPath * @return * @throws Exception */ public static String readParse(String urlPath) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream inStream = conn.getInputStream(); while ((len = inStream.read(data)) != -1) { outStream.write(data, 0, len); } inStream.close(); return new String(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据 } }
-
安卓!Adnroid Studio中怎样获取自己电脑上tomcat服务器里的json数据
2017-05-22 12:16:31现在获取这一步就获取不到,Log.d打印不出来,tomcat服务器已经开了,网络权限也配置了,通向tomcat的path也写了,但就是打印不出来,获取不到指定文件里的json数据。求大神解救啊!!!! 前三张是代码截图,第四张... -
Android中通过网络获取json数据来播放视频
2013-06-22 11:24:45为了实现 本地化的测试 ,要新建 一个java 类做为 服务端 让手机来访问 ...json数据 的内容 为: { "videos":[ { "id":"1", "title":"泡芙小姐的灯泡", "image":"http://172.22.64.28:8为了实现 本地化的测试 ,要新建 一个java 类做为 服务端 让手机来访问
把json放到你服务端tomcat 中 如图 :
json数据 的内容 为:
{ "videos":[ { "id":"1", "title":"泡芙小姐的灯泡", "image":"http://172.22.64.28:8080/doudou/images/fu.jpg", "duration":"910", "category":"原创", "state":"normal", "published":"2011-07-15 09:00:42", "description":"当一个人在一座城市搬11次家。就意味着准备在这个城市买房了", "player":"http://172.22.64.28:8080/doudou/video/oppo.3gp" }, { "id":"2", "title":"爱在春天", "image":"http://172.22.64.28:8080/doudou/images/spring.jpg", "duration":"910", "category":"原创", "state":"normal", "published":"2013-04-15 09:00:42", "description":"上世纪30年代中期,整个中国动荡不安,几个年轻女孩依然怀抱着勇气,追寻着理想与爱情。", "player":"http://172.22.64.28:8080/doudou/video/hao.3gp" } } }
public class ListVideoActivity extends Activity { // 获取视频数据的地址 private String path = "http://172.22.64.28:8080/doudou/video.json"; // 接受服务器端响应的数据 private String content; // 声明listView控件 private ListView listView; // 声明handler对象 private Handler handler; private static final int INTENTDATA = 1; public JSONArray array; public LayoutInflater inflater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_video); // 根据服务获取inflater对象 inflater = (LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE); // 发送请求 获取网络数据 sendGet(); // 获取控件对象 listView = (ListView) findViewById(R.id.lv_videos); // 实例化 handler操作 handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case INTENTDATA: // 获取数据操作 // 判断不为空 并且不等于"" if (content != null && (!"".equals(content))) { try { // 把它转换成json对象 {} [] JSONObject obj = new JSONObject(content); array = obj.getJSONArray("videos"); listView.setAdapter(new VideoAdapter());// 设置显示的视图 //listView注册事件 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { /** * parent :listView * view 每个条目控件 * position:条目所在的位置 * id:行号 0 */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { JSONObject jsonObj = (JSONObject) parent.getItemAtPosition(position); Intent intent = new Intent(ListVideoActivity.this,VideoViewActivity.class); try { intent.putExtra("path", jsonObj.getString("player")); startActivity(intent); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } catch (JSONException e) { System.out .println("------------exeception-------------" + e.getMessage()); } } break; default: break; } } }; } public void sendGet() { // 操作发送网络请求 new Thread(new Runnable() { @Override public void run() { content = HttpUtils.sendGetClient(path); // 发送消息 handler.sendEmptyMessage(ListVideoActivity.INTENTDATA); } }).start(); } class VideoAdapter extends BaseAdapter { @Override public int getCount() { return array.length(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub try { return array.get(position); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 创建一个显示的控件 每个条目对应的控件 // 根据inflate方法 把一个布局文件转换成View控件对象 View v = inflater.inflate(R.layout.activity_list, null); // findViewById()来获取View布局对象中的控件 TextView tv_title = (TextView) v.findViewById(R.id.tv_title); TextView tv_duration = (TextView) v.findViewById(R.id.tv_duration); TextView tv_date = (TextView) v.findViewById(R.id.tv_date); ImageView iv_icon = (ImageView) v.findViewById(R.id.iv_image); try { JSONObject jsonObj = (JSONObject) array.get(position); // 设置显示控件的文本 tv_title.setText("标题:" + jsonObj.getString("title")); tv_duration.setText("时长:" + jsonObj.getString("duration")); tv_date.setText("发布时间:" + jsonObj.getString("published")); iv_icon.setId(R.drawable.ic_launcher);// 默认的图标 } catch (Exception e) { System.out.println("eeeee" + e.getMessage()); e.printStackTrace(); } // 返回v对象 return v; } } }
public class VideoViewActivity extends Activity { private VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 控件 this.setContentView(R.layout.activity_videoview); videoView = (VideoView) findViewById(R.id.vv_video); String path = this.getIntent().getStringExtra("path"); if (path != null) { // 指定播放的视频文件即可 videoView.setVideoURI(Uri.parse(path)); System.out.println(path); // 设置视频播放的控制器 videoView.setMediaController(new MediaController(this)); // 视频开始播放 videoView.start(); } else { Toast.makeText(this, "path路径为空", Toast.LENGTH_LONG).show(); } } }
public class HttpUtils { /** * httpClient发送的GET请求 * * @param path * @return */ public static String sendGetClient(String path) { String content = null; try { // 创建一个httpClient的客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 发送的Get请求 HttpGet httpGet = new HttpGet(path); // 客户端 HttpResponse httpResponse = httpClient.execute(httpGet); // 判断服务端是否响应成功 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 获取响应的内容 InputStream is = httpResponse.getEntity().getContent(); byte data[] = StreamTools.isToData(is); content = new String(data); // 关闭流 is.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } /** * httpclient客户端发送Post请求 * @param path * @param name * @param pass * @return */ public static String sendPostClient(String path, String name, String pass) { String content = null; //创建一个httpClient对象 HttpClient httpClient = new DefaultHttpClient(); //创建请求方式对象 path HttpPost httpPost = new HttpPost(path); //封装请求的参数集合 List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("user.name", name)); parameters.add(new BasicNameValuePair("user.pass", pass)); UrlEncodedFormEntity entity = null; try { //封装请参数的实体对象 entity = new UrlEncodedFormEntity(parameters, "UTF-8"); //把参数设置到 httpPost中 httpPost.setEntity(entity); //执行请求 HttpResponse httpResponse = httpClient.execute(httpPost); //判断响应是否成功 if (httpResponse.getStatusLine().getStatusCode() == 200) { //获取响应的内容 InputStream is = httpResponse.getEntity().getContent(); //data byte data[] = StreamTools.isToData(is); //转换成字符串 content = new String(data); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } }
public class NetWorkUtils { private Context context; // 网路链接管理对象 public ConnectivityManager connectivityManager; public NetWorkUtils(Context context) { this.context = context; // 获取网络链接的对象 connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); } public boolean setActiveNetWork() { boolean flag =false; // 获取可用的网络链接对象 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo == null) { new AlertDialog.Builder(context) .setTitle("网络不可用") .setMessage("可以设置网络?") .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(context, "点击确认", Toast.LENGTH_LONG).show(); // 声明意图 Intent intent = new Intent(); intent.setAction(Intent.ACTION_MAIN); intent.addCategory("android.intent.category.LAUNCHER"); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings")); intent.setFlags(0x10200000); // 执行意图 context.startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show();// 必须.show(); } //判断网络是否可用 if(networkInfo!=null){ flag =true; } return flag; } }
public class StreamTools { public static byte[] isToData(InputStream is) throws IOException{ // 字节输出流 ByteArrayOutputStream bops = new ByteArrayOutputStream(); // 读取数据的缓存区 byte buffer[] = new byte[1024]; // 读取长度的记录 int len = 0; // 循环读取 while ((len = is.read(buffer)) != -1) { bops.write(buffer, 0, len); } // 把读取的内容转换成byte数组 byte data[] = bops.toByteArray(); bops.flush(); bops.close(); is.close(); return data; } }
<!-- 访问网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>完整代码请访问:http://download.csdn.net/detail/chrp99/5629565
-
简单的使用ajax获取json表格数据实例
2021-03-14 13:22:16简单的使用ajax获取json表格数据实例 这是一款简单的前端显示josn数据,主要介绍如何通过ajax调取josn数据并在页面上显示。友情提示: 在本地打开显示不出josn数据,请使用工具打开项目如:HBuilder、服务器、...简单的使用ajax获取json表格数据实例
这是一款简单的前端显示josn数据,主要介绍如何通过ajax调取josn数据并在页面上显示。友情提示: 在本地打开显示不出josn数据,请使用工具打开项目如:HBuilder、服务器、Tomcat等
-
使用OkHttp获取本地服务器目录下的json数据并解析为Bean对象
2020-07-25 19:37:52二、创建androidStudio工程三,获取json数据四.在界面中显示数据 一、 准备工作。 在apache服务器的C:\Tomcat 9.0\webapps\ROOT下准备一个简单的json文件,如图所示。并开启服务。 二、创建androidStudio工程 1.... -
(017)java后台开发之客户端通过HTTP获取接口Json数据
2018-01-11 17:11:13通过前面的文章,我们能了解javaWeb工程的基本...我们建立了JsonTest工程,部署到了tomcat,本地浏览器访问了我们的JsonTest工程的index.jsp页面。 那我们怎么进行客户端和服务器后台交互尼? 跟着一个例子实现: ... -
Android 手机卫士(5)从Apache Tomcat服务器获取数据并解析
2017-09-14 21:18:32我们从服务器端获取“信息”以便于CheckVersionCode,从而服务于版本更新操作!// 介绍一下流程: // 获取服务器端的版本号(两步:请求...// 以流的方式将响应数据[json文件里面的内容]读取出来// 提示更新的json文件应该 -
xutils +Gson解析json(从服务器中获取json并解析)
2016-04-23 11:59:20从服务器获取json函数“http://192.168.3.17:8080/newdata.json“是本地...2,tomcat默认端口是8080,如果想省略需要去tomcat的配置文件中去配置)vuperson 是首先定义好的bean对象 用来与json数据对应private void g -
springmvc获取activiti待办的json数据时报错了
2017-11-11 15:09:54at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: ... -
application/x-www-form-urlencoded tomcat 流获取不到数据
2019-12-02 19:37:03今天在调http接口的时候,对方的content-type 是 application/x-www-form-urlencoded ,然后我在接受的时候采用spring mvc 和tomcat,通过HttpServletRequest 获取输入流,通过输入流获取body数据,发现获取的数据为... -
python3处理json数据
2019-09-28 06:51:59获取actuator的值 [root@mongo_rs1 tmp]# cat test.py import requests import json url = 'http://wxtest.mayocase.com:8888/actuator/metrics/tomcat.sessions.active.max' payload = {'some': 'data'..... -
安卓使用FastJson解析Json数据并展示到ListView中
2017-02-26 14:54:38今天继续讲安卓端解析Json数据,数据存放在tomcat服务器,服务器端采用SSH框架编码完成,由安卓端通过http的GET请求获取到json对象数组,之后就是解析啦,解析完将所有数据存放在实体类中,接下来就是将数据显示在... -
微信小程序开发中遇到的问题(Json数据处理)
2020-03-21 23:39:23微信小程序之json数据处理 开发环境:微信开发者工具+eclipse+Tomcat+Mysql 功能描述:数据库返回给微信小程序前台一个对象的信息,前台要对该对象的信息处理,将该对象的各个属性值显示在wxml页面中。 困扰所在:... -
APP客户端访问SSH框架服务器返回json数据实例(服务端和客户端源码)
2015-01-21 19:51:55包含一个SSH框架实例和一个获取该服务器返回json数据的android app实例。 使用方法, 1.SHH是SSH框架的java wab工程,里面定义了一个action,启动apach-tomcat服务器后可在浏览器输入“localhost:8080/SSH/userjson... -
解决json传输数据的乱码问题
2018-09-08 19:58:53做的maven项目,tomcat服务器都是直接在pom中加的tomcat插件,前台模糊检索,不输入数据时能从solr中获取全部的数据,而加了关键字就获取不到了,打印查看原来是前台的ajax异步传入json数据时,在后台controller中获取出.... -
后台servlet怎么获取前台传来的json_JSON入门教程-Pt.0: Java 中 B/S 的数据传递
2020-12-09 11:02:36而在这研究两个问题之前,先研究 Java 中 浏览器端,也就是 JSP,与服务器端,也就是 Tomcat 的 Servlet 他们是如何进行数据传递的?看下面的例子!(如果很了解这个过程,可以草草看一下,或者直接跳过这个小节!)... -
Android连接JavaWeb服务端通过JSON进行数据交互
2020-06-16 11:24:56在浏览器通过请求地址成功获取响应的JSON数据 注意,接下来就是配置Android的请求地址了,Android的请求地址不能用127.0.0.1:8080,这是请求不到,而要通过本地电脑的实际IP地址。 打开DOS窗口,输入ipconfig... -
ajax post参数后台Tomcat 7获取不到的问题
2018-05-26 19:19:55网上找了各种方法,包括设置content-type,又是把json转成json格式字符串,问题依然存在,但是把post改成get又可以获取到,百思不得其解。后来看tomcat7配置的时候,把maxPostSize="0"的配置去掉的时候... -
unity能连jsp吗_Unity3D与JSP TomCat服务器传递数据和文件( 一 ) 建立Java服务器
2020-12-20 02:27:09资源分很多类型,如:json表,txt文件,image文件扫码关注微信公众号,获取最新资源 由于昨天手欠,直接点编辑,结果让二把一给覆盖了。。。导致我现在又重新写一遍。托更了半年,不是因为别的原因,是因为我找到了... -
基于jersey的pojo对象获取前台ajax的json参数
2012-03-29 13:57:04这里就不介绍Jersey了...我这里要说的是关于如何获取前台ajax请求的json数据。网上搜了很多都没有讲这一块的,要么都是用client来模拟,我这里测试成功了,先给出方法。 废话少说,先上代码: 首先是jsp页面ajax -
tomcat7以上,ajax post参数后台获取不到的问题
2017-03-08 11:20:00网上找了各种方法,包括设置content-type,又是把json转成json格式字符串,问题依然存在,但是把post改成get又可以获取到,百思不得其解。 后来看tomcat7配置的时候,把maxPostSize="0"的配置去掉的时候问题消失。 ... -
后台获取到的json字符串为iso-8859-1,怎么改为utf-8,
2020-03-19 11:55:15后端使用json数据需要:iso-8859-1 ---->>>utf-8 前端使用需要:utf--8----->>>iso-8859-1 @RequestMapping("changeCentre.action") ``` @RequestMapping("changeCentre.action") public void ... -
Android 获取网络数据(使用fastjson-1.2.3.jar 包)
2017-07-27 00:20:20在Tomcat/webapps\ROOT下新建一个JSON文件然后另存为修给编码格式为UTF-8 使用DOS密令在有网络的情况下执行ipconfig 获取到 IPv4 地址 后面一串ID 打开Tomcat 在浏览器输入http://(IPv4 地址):8080/(JSON...