我试图通过解析带有用户名和密码的登录网址来获取 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);
}
}
}
获取 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);
}
}
}
我感受到你的沮丧。
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"
}
它正在为我服务,希望这对其他人有帮助。
如果您以字符串形式获取服务器响应,则无需使用第三方库,您就可以做到
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
这是文档
否则要解析 json,您可以使用 Gson 或 Jackson
编辑没有库(未测试)
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");
}
}
}
在此代码片段中,我们将看到一个 volley 方法,添加以下依赖项应用程序级别的 gradle 文件
虚拟 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
不了解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);
}
}
AsyncTask 已弃用,因此请在 Activity 中使用
Executor
。
获取示例 JSON (http://ip-api.com/json),其中包含以下内容:
{"status":"success","country":"India","countryCode":"IN","region":"GJ","regionName":"Gujarat","city":"Surat","zip":"395007","lat":21.1888,"lon":72.8293,"timezone":"Asia/Kolkata","isp":"Reliance Jio Infocomm Limited","org":"Reliance Jio Infocomm Limited","as":"AS55836 Reliance Jio Infocomm Limited","query":"192.168.1.1"}
这在你的
Activity
:
final LocationItems[] locationItems = {new LocationItems()};
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
final String[] response = new String[1];
ProgressDialog progressDialog = new ProgressDialog(UploadActivity.this);
progressDialog.show();
executor.execute(() -> {
// Background work here
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://ip-api.com/json/").openConnection();
response[0] = Utils.convertStreamToString(con.getInputStream());
locationItems[0] = new LocationItems();
JSONObject object = new JSONObject(response[0]);
locationItems[0].city= object.getString("city");
locationItems[0].state=object.getString("regionName");
locationItems[0].country=object.getString("country");
// more string like;
} catch (Exception e){
locationItems[0].city="Mumbai";
locationItems[0].state="Maharashtra";
locationItems[0].country="India";
progressDialog.dismiss();
}
handler.post(() -> {
// UI Thread work here
// return locationItems;
Log.e("city", locationItems[0].city);
Log.e("state", locationItems[0].state);
Log.e("country", locationItems[0].country);
progressDialog.dismiss();
});
});
}
LocationItems.java
:
public class LocationItems {
public String city, state, country; // add more if needed
}
这里有一个转换为字符串的函数:
public static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next().replace(",", ",\n") : "";
}
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");
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));
}
}
}
我从 URL 读取 JSON 的相当短的代码。 (由于使用了
CharStreams
,因此需要番石榴)。
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 存储库的最新发行版本(基于标签名称)。