欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android studio http协议 HttpUrlConnection 解析json 调用服务器服务获得数据 批量插入数据库

程序员文章站 2024-02-04 20:09:58
...

Android studio http协议

HTTPPOST.java

package com.example.code;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HTTPPOST {
    public static String hqposjson(String urlStr, String postjson) {
        HttpURLConnection conn = null;
        InputStream inStream = null;
        PrintWriter printWriter = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-javascript; charset=utf-8");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            //conn.setRequestProperty("Content-Length", String.valueOf(postjson.length()));
            printWriter = new PrintWriter(conn.getOutputStream());
            printWriter.write(postjson);
            printWriter.flush();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inStream = new BufferedInputStream(conn.getInputStream());
            } else {
                inStream = new BufferedInputStream(conn.getErrorStream());
            }

            String result = iniotoString(inStream);
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (printWriter != null) {
                printWriter.close();
            }
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String iniotoString(InputStream is) {
        String line = "";
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8"));
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

**.java 调用 (http请求要开线程)

	//获取token
	String t="{\"user\":\"用户名\",\"password\":\"密码\"}";
	JSONObject obj= new JSONObject(HTTPPOST.hqposjson(tokenurl,t));
	String token=(String) obj.get("token");
	List data=new ArrayList();
	String tt="{\"token\":\""+token+"\",\"data\":"+data+"}";
	//http请求
	JSONObject document= new JSONObject(HTTPPOST.hqposjson(“网址”,tt));
	JSONArray jData=(JSONArray)document.get("data");
	//连接数据库
	DBHelper db=new DBHelper(Setting.this);
	SQLiteDatabase sqldb=db.getWritableDatabase();
	String sqlValuesSql="";
	int j=0;
	for(int i=0;i<jData.length();i++){
	   JSONObject p=(JSONObject)jData.get(i);
	   String cName = p.get("cName").toString();
	   String cValue = p.get("cValue").toString();
	   String cType = p.get("cType").toString();
	   String cContent = p.get("cContent").toString();
	   String cDefaultValue = p.get("cDefaultValue").toString();
	   int bIsVisiable;
	   if (p.get("bIsVisiable").equals("false")) {
	       bIsVisiable = 0;
	   } else {
	       bIsVisiable = 1;
	   }
	   //批量插入数据库sql
	   sqlValuesSql=sqlValuesSql+" select '"+cName+"','"+cValue+"','"+cType+"','"+cContent+"','"+bIsVisiable+"','"+cDefaultValue+"' union all  ";
	   j=j+1;
	   if(j>=400){
	        //System.out.print(sqlValuesSql);
	        sqlValuesSql=sqlValuesSql.substring(0,sqlValuesSql.length()-11) ;
	        sqldb.execSQL(sqlStr+sqlValuesSql) ;
	        j=0;
	        sqlValuesSql="";
	    }
	 }
	 if (sqlValuesSql !="")
	 {
	      sqlValuesSql=sqlValuesSql.substring(0,sqlValuesSql.length()-11) ;
	      sqldb.execSQL(sqlStr+sqlValuesSql) ;
	  }
	  db.close();
	  if("ok".equals(document.get("flag").toString())) {
	                System.out.println("请求成功");
	            }else{
	                new Thread(new Runnable() {
	                    @Override
	                    public void run() {
	                        Handler handler = new Handler(Looper.getMainLooper());
	                        handler.post(new Runnable() {
	                            @Override
	                            public void run() {
	                                //放在UI线程弹Toast
	                                Toast.makeText(Setting.this, "获取数据失败!", Toast.LENGTH_LONG).show();
	                            }
	                        });
	                    }
	                }).start();
	            }