gpt4 book ai didi

java - 如果网络可用,则从服务器获取 JSON

转载 作者:行者123 更新时间:2023-12-01 19:29:38 26 4
gpt4 key购买 nike

如何使用负变量值从 Internet 加载文件,以及使用正值变量从手机上的文件加载文件?

它应该像这样工作:

我的系统检查是否有互联网

如果没有,则从内存加载

如果有,则从站点url加载

public String getJSONFromAssets(Context context) {
String json = null;
try {
InputStream inputData = context.getAssets().open("data.json"); //load assets file
//Log.e("100rad", ":"+inputData);
int size = inputData.available();
byte[] buffer = new byte[size];
inputData.read(buffer);
inputData.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected JSONArray doInBackground(String... strings) {
String stationsJsonString = getJSONFromAssets(MainActivity.this);
try {
JSONArray stationsJsonArray = new JSONArray(stationsJsonString);
return stationsJsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
//This will only happen if an exception is thrown above:
return null;
}

protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("store_name");
String lat=jsonObject.getString("latitude");
String lang=jsonObject.getString("longitude");
String desc=jsonObject.getString("store_desc");
String oxr=jsonObject.getString("telephone");
String sost=jsonObject.getString("keywords");
int cat=jsonObject.getInt("category_id");
int id=jsonObject.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}

最佳答案

这是 JSONParser 类

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {

sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}

if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Accept-Charset", charset);

conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);

conn.connect();

paramsString = sbParams.toString();

wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();

} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET

if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}

try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(false);

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept-Charset", charset);

conn.setConnectTimeout(15000);

conn.connect();

} catch (IOException e) {
e.printStackTrace();
}

}

try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}

Log.d("JSON Parser", "result: " + result.toString());

} catch (IOException e) {
e.printStackTrace();
}

conn.disconnect();

// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON Object
return jObj;
}}

关于java - 如果网络可用,则从服务器获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60146231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com