Source not found error after HttpClient.execute() - java

I am new to android development. I have the following class for downloading some data in JSON format. I keep getting a Source not found error on the
HttpResponse httpResponse = httpClient.execute(httpPost);
line... I'm sure this must be a simple fix... Here is the class code...
package com.example.tankandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject 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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}

Put this code in onCreate method
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);

Use Apache HttpCore and HttpClient libraries. Put these two libraries into your lib folder, its automatically add these into your build path.

One reason for this situation may be missing internet permissions in AndroidManifest.xml file. Adding this line in manifest will fix the issue.
<uses-permission android:name="android.permission.INTERNET" />

You need to provide some more information I think. Where do you get the "Source not found" error? Is it an Eclipse error that prevents you from compiling. Is it during compilation? Is it a runtime error? Could this be a possible duplicate of: Source not found Android? ?
Question: Why are you doing an HTTP POST if you don't intend to add any POST data? A GET seems more appropriate.
And since you also ask "I'm sure this must be a simple fix" then yes, it is. I'd really suggest that you rip out your HTTP code and switch to Android Asynchronous Http Client. It's super easy to work with and very well suited for getting an HTTP response and parsing it. Example:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("some_param", "some value");
rp.put("another_param", "some other value");
client.post("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
#Override
public final void onSuccess(String response) {
// handle your response and parse JSON here
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
}
});
or GET:
client.get("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
...
}
And finally if you want to simplify JSON parsing have a look at Jackson or Gson. Especially if you want to parse JSON data to Java objects and vice versa.

Related

Parsing extremely simple JSON from a URL in in Android

I have tried everything online to try to parse this JSON but nothing seems to work. Here is the JSON:
{"salonphoebe":true,"salonvo":false}
That's it. It is only booleans. It is from an HTTP website if that is important at all.
How do I do parse this extremely simple JSON from http://example.com in Java in Android Studio? I am trying to create Booleans based on these in my app. I know this question is on this website a lot but I have literally tried 10 solutions but nothing will work. Thank you.
Try the following code.
try {
JSONObject json = new JSONObject(your - json - string - here);
boolean b1 = json.optBoolean("salonphoebe");
boolean b2 = json.optBoolean("salonvo");
} catch (JSONException e) {
e.printStackTrace();
}
Okay I have solved my own problem. Here is everything I learned and what I did. I want to help anyone else with this problem if they come across this issue. First I added this to my androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Then I added this between the tags in the androidmanifest.xml beucase the link I am parsing the JSON from is an HTTP link:
android:usesCleartextTraffic="true"
Really quickly import all of this into your mainactiviy.java:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
Then we get into the hard stuff. There are two parts to parsing JSON data from the internet. First, you must read the JSON (meaning put the JSON from online into a String) from the URL and then you must organize the String of JSON into separate variables. So let's start on the HTTP Request. I created an Async class in my MainActivity.java (under the OnCreate) that I found online that looks like this:
public class HttpGetRequest extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String url = "http://example.com/example.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
System.out.println("Test");
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String jsonResponse = response.toString();
return jsonResponse;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
boolean myJsonBool = json.optBoolean("samplestringinyourjson");
if(hasPaid){
//do something
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Okay so basically the reason we put this in an Async class is because java won't let you make an HTTP Request in your OnCreate. What the doInBackground is doing is fetching the JSON data and putting it into the string like I said. The OnPostExecute is separating that string into boolean values and doing stuff with it. Lastly, paste this into your OnCreate or it won't work:
new HttpGetRequest().execute();
That's it. If you have questions ask and hopefully I can see it.

Error parsing dataorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

i'm trying to make android food order for my thesis and because this error i'm running out of time :(
error on logcat :
Error parsing dataorg.json.JSONException: Value cannot be converted to JSONObject
org.json.JSONException: Value to JSONObject
here's my JSONParser :
package com.makanan.restotradisional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// fungsi abil json url lewat method HTTP POST atau GET
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
// jika request method adalah POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// jika request method adalah GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data" + e.toString());
e.printStackTrace();
}
return jObj;
}
}
this my PHP & Java : http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html
and this is my database on phpmyadmin :http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html
please help me
Remove any of the <br> statements or echo statements from your php file except the one that you are using to pass json..
Check the output of your file in browser, remove all the unwanted things other than json..
Please print and check if your string json is in right format as expected by the JSONObject constructor. Per documentation, valid json string to construct JSONObject should be -- A string beginning with { (left brace) and ending with } (right brace).
Please refer this.
Go inside JSONParser and do this so u see in logcat whats comming from php. Probably its a php error.
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
//This line is what u need to add
Log.d("Whats wrong?", json.toString());
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

The most basic HttpGet request on Java

I need help performing a RESTful call to a website that returns a JSON object. I'm stuck with the options that are available but I would prefer to use something that comes right out of the box and not install any third party plugins.
Here's what I currently have so far:
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGetRequest = new HttpGet("http://search.twitter.com/search.json?q=%40apple");
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
I know that the URL used in this example returns the following:
{"errors":[{"message":"The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.","code":64}]}
Which is fine by me, I just want to at least convert the JSON response into a string so that I can move on from here. I'm very familiar to how REST works and it's been pretty easy to get it working on Objective-C and Python but Java for some reason has a dozen implementations for getting it to work properly, I'm just looking for the most basic approach possible, I'm not doing anything crazy like uploading images to a server.
So the issue with my code above is that I'm getting a ClientProtocolException error and the httpClient.execute() requires a try catch statement, this is something brand new to me, I've never had a compiler yell at me for not inserting try catch statements.
How can I fix this to call a url that converts a very basic JSON object to a string?
This code should work:
try {
HttpResponse response;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getConnection = new HttpGet(url);
try {
response = httpClient.execute(getConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
JSONObject jsonObject = new JSONObject(JSONString); //Assuming it's a JSON Object
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}

JSON reads me only objects, no arrays

I'm using Eclipse, for an application where I have to read a JSON file from an URL.
The code I'm using is this one:
http://collegewires.com/android/2012/06/json-parsing-in-android/
Ok, the CLASS which I'm using for reading JSON files is called Parser.java:
package com.cw.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class Parser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
// class constructor
public Parser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// Parsing the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
// JSON String
return jsonObject;
}
}
I was using this code for reading a JSON file which is directly an ARRAY, but the code gives me an error.
My question is: is it possible to read an Array instead always reading an Object??
maybe using another class?
Try to modify your Parser.java to this, so you gat a Array not a Object. And please buy you a JAVA Book for beginners, so you do learn how to speak JAVA
public JSONArray getJSONFromUrl(String url) {
....
static JSONArray jsonArray = null;
....
// Parsing the string to a JSON Array
try {
jsonArray = new JSONArray(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
return jsonArray;
}

How do I check the contents of a String Builder

I am trying to parse some JSON and send it to a EditText field in my android application. I recently discovered that an error I was getting was stemming from the contents of my StringBuilder. Instead of using my StringBuilder I hardcoded a sample of json into a string and sent that to the EditText field. That works fine and I get the value I am looking for to show up. However I need this to work via accessing the API I am using and not hardcoding. Below is my JSON Parser class. Is there a way I can check what is in my stringBuilder after the append before inputStream is closed. This way I can sort that out and return my jSon back to stringBuilder.toString() instead of hardcoding it.
package com.apitest.rottentomatoestest;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.util.Log;
public class JSONParser {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public JSONParser() {
// TODO Auto-generated constructor stub
}
public JSONObject getJSONFromUrl(String url){
//Make HTTP Request
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
jSon = "{\"cast\":[{\"id\":\"162661723\",\"name\":\"Snoop Dogg\"}]}";
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
You can use:
Log.d("JSON Contents", stringBuilder.toString());
just before you close the inputStream.
Update: The 596 Service Not Found message is often caused by an incorrect URL.
try doing this instead :
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
You can use org.json.JSONObject for parsing JSON into usable Java Object.

Categories

Resources