I am trying to get JSON data by parsing login url with username and password. I have tried by using below code but I can't get any responses. Please help me.
I am using HTTP Process and API level 23.
I need to parse my URL and get below Response
{
"response":{
"Team":"A",
"Name":"Sonu",
"Class":"First",
},
"Result":"Good",
}
Below My code :
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);
}
}
}
This question is related to
android
json
android-6.0-marshmallow
Don't know about android but in POJ I use
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);
}
}
Here in this snippet, we will see a volley method, add below dependency in-app level gradle file
Dummy URL -> https://jsonplaceholder.typicode.com/users (HTTP GET Method Request)
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;
}
Visit https://github.com/JainaTrivedi/AndroidSnippet-/blob/master/Snippets/VolleyActivity.java
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");
Easy way to get JSON especially for 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);
}
}
}
My fairly short code to read JSON from an URL. (requires Guava due to usage of 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: This code gets the latest release version (based on tag name) for a given GitHub repo.
If you get the server response as a String, without using a third party library you can do
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
Here is the documentation
Otherwise to parse json you can use Gson or Jackson
EDIT without libraries (not tested)
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");
}
}
}
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));
}
}
}
I feel your frustration.
Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.
That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.
(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)
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);
}
}
}
}
This would be the json object it is targeted towards.
{
"yourJsonElement":"Hi, I'm a string",
"anotherElement":"Ohh, why didn't you pick me"
}
It is working on my end, hope this is helpful to someone else out there.
Source: Stackoverflow.com