Why can't read this json, but Browser can - java

I don't understand why can't I read this json link but Browser Chrome can read, I tried with different link and I read them.
this is the link for requesting json response:
My Code:
runOnUiThread(new Runnable() {
#Override
public void run() {
new sendToken().execute("http://admin:123#qlvb-snv.newsaigonsoft.com/push-notifications-portlet/api/secure/jsonws/pushnotificationsdevice/add-push-notifications-device?token=cNAXYNQSPHk:APA91bF86THzkPE_ol9euea1M40x6jVgN9RjUOISVtL-UEXDYpAP62aeRnUwkLrSt6z8C4saTJPKW5CJ57VSRmovZ5OBX4NsZg3U-zoDdXB64dWzAQGB7WllGvqGEO3Nt4_Fbg-vUyok&platform=android");
}
});
and My AsyncTask:
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return docNoiDung_Tu_URL(params[0]);
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s + "");
}
}
and it does not respond with anything.

Two things may be the cause
either your method
docNoiDung_Tu_URL is not correct or correctly written
or, You have no permissions to access Internet.

change your doInBackground Like this
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = getNewHttpClient();
HttpGet httpget = new HttpGet(arg0[0]);
// Execute HTTP get Request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return responseString;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s);
}
Also add the dependencies to build.gradle
compile('org.apache.httpcomponents:httpcore:4.4.1') {
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
don't forget to add the internet permission to manifest
<uses-permission android:name="android.permission.INTERNET"/>

you have to make http call
HttpURLConnection urlConnection = null;
String My_URL = "YOUR URL";
BufferedReader reader = null;
URL url = null;
String Json;
InputStreamReader inputStream1 = null;
InputStream inputStream = null;
inside do in background
#Override
protected String doInBackground(Void... params) {
try {
url = new URL(My_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if(urlConnection.getResponseCode() == 200)
{
inputStream = urlConnection.getInputStream();
Json = readData(inputStream);
}
else {
urlConnection.getResponseCode();
}
}catch (Exception e){
Json = e.toString();
}
finally {
if (urlConnection!=null)
urlConnection.disconnect();
try {
if (inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return Json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// your work
}
public String readData(InputStream inputStream)
{
StringBuilder builder = new StringBuilder();
try {
if (inputStream != null) {
inputStream1 = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStream1);
String line = reader.readLine();
while (line != null) {
builder.append(line);
line = reader.readLine();
}
} else {
Toast.makeText(MainActivity.this, "errorwa", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){}
return builder.toString();
}

You can not directly read the response from the url.
Try out below code:
public JSONObject getJSONFromUrl(String url) {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Add the below permission in manifest
<uses-permission android:name="android.permission.INTERNET"/>

Related

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

IOException error to connect to wamp server with eclipse?

I have a problem with connecting to WAMP server with my android program that I made with eclipse....
This is my class:
public class Webservice {
public static String readurl(String url)
{
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String resault = ConvertInputStream(inputStream);
return resault;
}
catch (ClientProtocolException e) {
//e.printStackTrace();
Log.i("Log", "Protocol");
}
catch (IOException e) {
//e.printStackTrace();
Log.i("Log", "IOException");
}
return "read";
}
private static String ConvertInputStream(InputStream inputStream)
{
try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
return builder.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And this is my activity code:
public class NotesActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String resault = Webservice.readurl("http://localhost/note-server");
Log.i("Log", "Resault: " + resault);
When I run, it gives me "IOException" because of the "Log" in my class under the IOException, and at the end give me "Result: read"!!!!!
How can I fix that?
If you are running on an emulator then you should use 10.0.2.2 instead of localhost.
See this post.

How to get Java script variable from HTML using HttpClient

I need to get the js variable from HTML. I get html from server using HttpCLient, and try to search "src" in stringBuilder.
I want to get image URL shown on page.
Thml sting that i parsed.
How to get this variable?
< img id="h5" src="8.jpg" border="0">
#Override
protected String doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
httpclient = new DefaultHttpClient(httpParameters);
httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Encoding", "gzip");
//Запрос
HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = response.getEntity().getContent();
} catch (IOException e) {
e.printStackTrace();
}
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null) && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
try {
instream = new GZIPInputStream(instream);
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(instream, "utf-8"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.contains("\" src"))
{
sb.append(line).append("\n");
}}
} catch (IOException e) {
e.printStackTrace();
}
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
Log.i("Do id back", " ");
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
txtUrl.setText(result.toString());
Log.i("on Post"," ");
}
}
You can use an HTML parser, e.g. jsoup.

reading JSON data from URL

I am trying to parse some JSON data, but my app doesn't do anything because i can't seem to get any response from URL, i tried to open URL connection in few different ways, but it's still the same. for Example :
urlMy=new URL(string);
URLConnection tc = urlMy.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line=in.readLine();
doesn't return anything, it even dismisses everything in my function written below that code.
Or
urlMy=new URL(examp);
InputStream inputStream = urlMy.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bR = new BufferedReader(reader);
the same thing. This function is called and like it never happend, every function after this one executes, so it's not in the endless loop, but every bit of code in this function after this example code is ignored. if i remove this code for reading url, everthing else works.
Try to use AsyncTask,try something like:
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com"
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
In the last Google I/O, Google released a new library called Volley. It's fast for HTTP requests, very easy to use and you can set it up to return JSONObjects ready for parsing. https://developers.google.com/events/io/sessions/325304728

Json Parsin in android

http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews
This is my web service. I want to parse it and I want show news_id and news title. Please post, showing me how to parse it so that I can store all the values in a string. I tried but am getting Exception ..
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
// String name;
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
json_data = jArray.getJSONObject(i);
// name=json_data.getString("name");
map.put("id", String.valueOf(json_data.getString("news_id")));
map.put("title",json_data.getString("news_title"));
map.put("shortdescription",json_data.getString("news_short_description"));
map.put("date",json_data.getString("news_date"));
mylist.add(map);
}
}
catch(Exception e)
{
}
}
You can parse using Gson parser.
So first download gson-1.1.jar file from http://findjar.com/jar/com/google/code/gson/gson/1.1/gson-1.1.jar.html
and then add jar file into your project build path then use the below code for parsing (Simple replace your parsing code with below code)
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.taxmann.com/TaxmannWhatsnewService/Services.aspx?service=getStatutesTabNews");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Gson gson = new Gson();
Type collectionType = new TypeToken<List<NewsData>>(){}.getType();
List<NewsData> details = gson.fromJson(data, collectionType);
}
catch (Exception e)
{
Log.i("error","error");
e.printStackTrace();
}
bean for above code is
public class NewsData
{
private String news_id = null;
private String news_title = null;
private String news_short_description = null;
private String news_date = null;
public String getNews_id()
{
return news_id;
}
public void setNews_id(String newsId)
{
news_id = newsId;
}
public String getNews_title()
{
return news_title;
}
public void setNews_title(String newsTitle)
{
news_title = newsTitle;
}
public String getNews_short_description()
{
return news_short_description;
}
public void setNews_short_description(String newsShortDescription)
{
news_short_description = newsShortDescription;
}
public String getNews_date()
{
return news_date;
}
public void setNews_date(String newsDate)
{
news_date = newsDate;
}
}
and add internet permission in your manifest
<uses-permission
android:name="android.permission.INTERNET" />
I hope this will help you.
if you still not get your result you can use below code .
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jsonArray=null;
static String json = "";
mJsonArray=getJSONFromUrl(url);
try{
JSONObject mJsonObject=null;
for(int i =0;i<mJsonArray.length();i++){
if(!mJsonArray.isNull(i)){
HashMap<String, String> map = new HashMap<String, String>();
mJsonObject=mJsonArray.getJSONObject(i);
map.put("title",mJsonObject.getString("news_title"));
map.put("shortdescription",mJsonObject.getString("news_short_description"));
map.put("date",mJsonObject.getString("news_date"));
//add you map in to list
}
}
}catch(JSONException jexc){
jexc.printStackTrace();
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jsonArray =new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonArray;
}

Categories