【问题标题】:Get JSON Data from URL Using Android?使用 Android 从 URL 获取 JSON 数据?
【发布时间】:2016-01-18 17:05:40
【问题描述】:

我正在尝试通过使用用户名和密码解析登录 url 来获取 JSON 数据。我已经尝试使用下面的代码,但我无法得到任何响应。请帮帮我。

我正在使用 HTTP 进程和 API 级别 23。

我需要解析我的 URL 并得到下面的响应

{
    "response":{
                "Team":"A",
                "Name":"Sonu",
                "Class":"First",
              },
                "Result":"Good",
}

在我的代码下面:

public class LoginActivity extends Activity {

    JSONParser jsonparser = new JSONParser();
    TextView tv;
    String ab;
    JSONObject jobj = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        new retrievedata().execute();

    }

    class retrievedata extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            jobj = jsonparser.makeHttpRequest("http://myurlhere.com");

            // check your log for json response
            Log.d("Login attempt", jobj.toString());

            try {
                ab = jobj.getString("title");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return ab;
        }
        protected void onPostExecute(String ab){

            tv.setText(ab);
        }

    }

}

【问题讨论】:

标签: android json android-6.0-marshmallow


【解决方案1】:

如果您将服务器响应作为字符串获取,则无需使用第三方库即可

JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");

这里是documentation

否则解析json你可以使用Gson或者Jackson

EDIT 没有库(未测试)

class retrievedata extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("http://myurlhere.com");
            urlConnection.setRequestMethod("GET"); //Your method here 
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            exception = e;
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    exception = e;
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = new JSONObject(response);
            JSONObject jsonResponse = json.getJSONObject("response");
            String team = jsonResponse.getString("Team");
        }
    }
}

【讨论】:

    【解决方案2】:
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String sResponse;
    StringBuilder s = new StringBuilder();
    
    while ((sResponse = reader.readLine()) != null) {
        s = s.append(sResponse);
    }
    Gson gson = new Gson();
    
    JSONObject jsonObject = new JSONObject(s.toString());
    String link = jsonObject.getString("Result");
    

    【讨论】:

      【解决方案3】:

      我感受到你的沮丧。

      Android 非常分散,网络上大量不同的示例在搜索时无济于事。

      也就是说,我刚刚完成了一个部分基于 mustafasevgi 样本的样本, 部分来自其他几个stackoverflow答案,我尝试以最简单的方式实现此功能,我觉得这接近目标。

      (请注意,代码应该易于阅读和调整,因此它不能完全适合您的 json 对象,但应该超级容易编辑,以适应任何场景)

      protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
      {
          @Override
          protected JSONObject doInBackground(Void... params)
          {
      
              String str="http://your.domain.here/yourSubMethod";
              URLConnection urlConn = null;
              BufferedReader bufferedReader = null;
              try
              {
                  URL url = new URL(str);
                  urlConn = url.openConnection();
                  bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
      
                  StringBuffer stringBuffer = new StringBuffer();
                  String line;
                  while ((line = bufferedReader.readLine()) != null)
                  {
                      stringBuffer.append(line);
                  }
      
                  return new JSONObject(stringBuffer.toString());
              }
              catch(Exception ex)
              {
                  Log.e("App", "yourDataTask", ex);
                  return null;
              }
              finally
              {
                  if(bufferedReader != null)
                  {
                      try {
                          bufferedReader.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
      
          @Override
          protected void onPostExecute(JSONObject response)
          {
              if(response != null)
              {
                  try {
                      Log.e("App", "Success: " + response.getString("yourJsonElement") );
                  } catch (JSONException ex) {
                      Log.e("App", "Failure", ex);
                  }
              }
          }
      }
      

      这将是它所针对的 json 对象。

      {
          "yourJsonElement":"Hi, I'm a string",
          "anotherElement":"Ohh, why didn't you pick me"
      }
      

      它正在为我工​​作,希望这对其他人有帮助。

      【讨论】:

      • 如何在我的主类中调用它
      • 现在是 2021 年,这仍然很重要。伙计,我想念编写 ajax 请求的简单日子。谢谢,现在剩下的就是将其重构为漂亮整洁的东西
      【解决方案4】:

      获取 JSON 的简单方法,尤其适用于 Android SDK 23

      public class MainActivity extends AppCompatActivity {
      
      Button btnHit;
      TextView txtJson;
      ProgressDialog pd;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
      
          btnHit = (Button) findViewById(R.id.btnHit);
          txtJson = (TextView) findViewById(R.id.tvJsonItem);
      
          btnHit.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  new JsonTask().execute("Url address here");
              }
          });
      
      
      }
      
      
      private class JsonTask extends AsyncTask<String, String, String> {
      
          protected void onPreExecute() {
              super.onPreExecute();
      
              pd = new ProgressDialog(MainActivity.this);
              pd.setMessage("Please wait");
              pd.setCancelable(false);
              pd.show();
          }
      
          protected String doInBackground(String... params) {
      
      
              HttpURLConnection connection = null;
              BufferedReader reader = null;
      
              try {
                  URL url = new URL(params[0]);
                  connection = (HttpURLConnection) url.openConnection();
                  connection.connect();
      
      
                  InputStream stream = connection.getInputStream();
      
                  reader = new BufferedReader(new InputStreamReader(stream));
      
                  StringBuffer buffer = new StringBuffer();
                  String line = "";
      
                  while ((line = reader.readLine()) != null) {
                      buffer.append(line+"\n");
                      Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 
      
                  }
      
                  return buffer.toString();
      
      
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  if (connection != null) {
                      connection.disconnect();
                  }
                  try {
                      if (reader != null) {
                          reader.close();
                      }
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              return null;
          }
      
          @Override
          protected void onPostExecute(String result) {
              super.onPostExecute(result);
              if (pd.isShowing()){
                  pd.dismiss();
              }
              txtJson.setText(result);
          }
      }
      }
      

      【讨论】:

      • 谢谢,完美。请注意,result 在没有可用网络时也是一个空字符串。
      • 这太棒了!我是 Android 的新手,一开始我不清楚的几件事是你需要 import java.io.BufferedReader;导入 java.io.IOException;导入 java.io.InputStream;导入 java.io.InputStreamReader;导入 java.net.HttpURLConnection;导入 java.net.MalformedURLException;导入 java.net.URL;而且一开始并不明显“.execute()”是运行它的方法lol
      • 非常感谢,这对我帮助很大,顺便说一句,我可以发送特定的方法,如 POST、PUT 等吗?
      【解决方案5】:

      在这个 sn-p 中,我们将看到一个 volley 方法,在应用内级别的 gradle 文件下面添加依赖

      1. 编译 'com.android.volley:volley:1.1.1' -> 添加 volley 依赖项。
      2. implementation 'com.google.code.gson:gson:2.8.5' -> 为 Android 中的 JSON 数据操作添加 gson。

      虚拟 URL -> https://jsonplaceholder.typicode.com/users(HTTP GET 方法请求)

      public void getdata(){
          Response.Listener<String> response_listener = new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                  Log.e("Response",response);
                  try {
                      JSONArray jsonArray = new JSONArray(response);
                      JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONObject("address").getJSONObject("geo");
                      Log.e("lat",jsonObject.getString("lat");
                      Log.e("lng",jsonObject.getString("lng");
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
          };
      
      
          Response.ErrorListener response_error_listener = new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                  if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                      //TODO
                  } else if (error instanceof AuthFailureError) {
                      //TODO
                  } else if (error instanceof ServerError) {
                      //TODO
                  } else if (error instanceof NetworkError) {
                      //TODO
                  } else if (error instanceof ParseError) {
                      //TODO
                  }
              }
          };
      
          StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://jsonplaceholder.typicode.com/users",response_listener,response_error_listener);
          getRequestQueue().add(stringRequest);
      }   
      
      public RequestQueue getRequestQueue() {
          //requestQueue is used to stack your request and handles your cache.
          if (mRequestQueue == null) {
              mRequestQueue = Volley.newRequestQueue(getApplicationContext());
          }
          return mRequestQueue;
      }
      

      访问https://github.com/JainaTrivedi/AndroidSnippet-/blob/master/Snippets/VolleyActivity.java

      【讨论】:

        【解决方案6】:

        不了解android,但我在POJ中使用

        public final class MyJSONObject extends JSONObject {
            public MyJSONObject(URL url) throws IOException {
                super(getServerData(url));
            }
            static String getServerData(URL url) throws IOException {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String text = ir.lines().collect(Collectors.joining("\n"));
                return (text);
            }
        }
        

        【讨论】:

          【解决方案7】:
          private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {
          
              @Override
              protected void onPreExecute() {
          
              }
          
              @Override
              protected JSONObject doInBackground(String... urls) {
                  if (urls.length > 0) {
                      String url = urls[0];
                      HttpClient httpClient = new DefaultHttpClient();
                      HttpGet httpget = new HttpGet(url);
                      httpget.setHeader("x-li-format", "json");
                      try {
                          HttpResponse response = httpClient.execute(httpget);
                          if (response != null) {
                              //If status is OK 200
                              if (response.getStatusLine().getStatusCode() == 200) {
                                  String result = EntityUtils.toString(response.getEntity());
                                  //Convert the string result to a JSON Object
                                  return new JSONObject(result);
                              }
                          }
                      } catch (IOException e) {
          
                      } catch (JSONException e) {
                      }
                  }
                  return null;
              }
              @Override
              protected void onPostExecute(JSONObject data) {
                  if (data != null) {
                      Log.d(TAG, String.valueOf(data));
                  }
              }
          
          }
          

          【讨论】:

            【解决方案8】:

            我从 URL 读取 JSON 的相当短的代码。 (由于使用了CharStreams,因此需要 Guava)。

                private static class VersionTask extends AsyncTask<String, String, String> {
                    @Override
                    protected String doInBackground(String... strings) {
                        String result = null;
                        URL url;
                        HttpURLConnection connection = null;
                        try {
                            url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                            connection = (HttpURLConnection) url.openConnection();
                            connection.connect();
                            result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
                        } catch (IOException e) {
                            Log.d("VersionTask", Log.getStackTraceString(e));
                        } finally {
                            if (connection != null) {
                                connection.disconnect();
                            }
                        }
                        return result;
                    }
            
                    @Override
                    protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        if (result != null) {
                            String version = "";
                            try {
                                version = new JSONObject(result).optString("tag_name").trim();
                            } catch (JSONException e) {
                                Log.e("VersionTask", Log.getStackTraceString(e));
                            }
                            if (version.startsWith("v")) {
                                //process version
                            }
                        }
                    }
                }
            

            PS:此代码获取给定 GitHub 存储库的最新发布版本(基于标签名称)。

            【讨论】:

              猜你喜欢
              • 2015-04-08
              • 1970-01-01
              • 1970-01-01
              • 2019-01-19
              • 2013-07-14
              • 2023-04-04
              • 2023-03-21
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多