HttpURLConnection .getInputStream() Crashes on Marshmallow not Oreo - android

The following code works flawlessly on Android 8. On a tablet running 6 it crashes when getting the getinputstream with a file io error. I've tried for HOURS and HOURS without any luck. PLEASE help. Nothing works. Even trying a volley doesn't help. My Web API works great on a computer and a phone.
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://api.github.com/users/dmnugent80/repos");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
catch(Exception e) {
e.printStackTrace();
}
return result.toString();
}
LOG CAT HERE
06-24 02:01:21.813 22840-22890/com.marcusengineering.recipedatabase
I/System.out: [CDS][DNS] getAllByNameImpl netId = 0 06-24 02:01:21.813
22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
[getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
netid=0; mark=0
[getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0 06-24 02:01:21.817
22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
[getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
netid=0; mark=0 06-24 02:01:21.818
22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
[getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024;
ai_family=0 06-24 02:01:21.824
22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
getaddrinfo: recipedatabase.gear.host get result from proxy gai_error
= 0 06-24 02:01:21.824 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
timeout:0 06-24 02:01:21.826
22840-22890/com.marcusengineering.recipedatabase I/System.out:
[socket][0] connection
recipedatabase.gear.host/204.246.56.80:80;LocalPort=43028(0)
[CDS]connect[recipedatabase.gear.host/204.246.56.80:80] 06-24 02:01:21.826 22840-22890/com.marcusengineering.recipedatabase D/Posix:
[Posix_connect Debug]Process com.marcusengineering.recipedatabase :80
06-24 02:01:21.919 22840-22890/com.marcusengineering.recipedatabase
I/System.out: [CDS]port[43028]
[socket][/192.168.1.163:43028] connected 06-24 02:01:21.920 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
timeout:0
[CDS]SO_SND_TIMEOUT:0 06-24 02:01:21.921 22840-22890/com.marcusengineering.recipedatabase I/System.out:
[OkHttp] sendRequest>>
[OkHttp] sendRequest<< 06-24 02:01:21.982 22840-22890/com.marcusengineering.recipedatabase W/System.err:
java.io.FileNotFoundException:
http://recipedatabase.gear.host/RestServiceImpl.svc/jsonfindtable/SELECT
UnitID, UnitName, HiddenFlag FROM TblUnits ORDER BY UnitName FOR JSON
PATH
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.marcusengineering.recipedatabase.MainActivity.getRestFromWebAsString(MainActivity.java:334)
at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:252)
at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:232)
at android.os.AsyncTask$2.call(AsyncTask.java:295) 06-24 02:01:21.983 22840-22890/com.marcusengineering.recipedatabase
W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

FINNNNNNNALY FIGURED IT OUT!.
Not sure which ones were 100% needed but here's what I did to help any other poor souls.
Ensure that your web api is fomratted without the extra wrapping added from WCF, i.e. is plain text. (not critical)
Get rid of spaces in your URL. It appears OREO does this for you. Earlier versions must not. The code to do this is: URL url = new URL(query.replace(" ","%20"));
Happy dance
In totality the call should be as follows:
URL url = new URL(query.replace(" ","%20"));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int i = urlConnection.getResponseCode();
InputStream inputs;
if (i < HttpURLConnection.HTTP_BAD_REQUEST) {
inputs = urlConnection.getInputStream();
} else {
// Error
inputs = urlConnection.getErrorStream();
return "-1";
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
result.append(line);
}
To set the formatting to raw string in the WCF see the following.
In the *****.cs
[OperationContract]
[WebGet( UriTemplate = "jsonFindTableBare/{id}")]
Stream DoWork(string id);
In the svc.cs
public Stream DoWork(String id)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
String str = "YOUR RESPONSE HERE";
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return new MemoryStream(Encoding.UTF8.GetBytes(str));
}
Thanks for all the help, Mangal. Appreciate it.

You should first check response code to also handle the error input stream.
InputStream inputs;
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
inputs = urlConnection.getInputStream();
} else {
// Error
inputs = urlConnection.getErrorStream();
}
then call
InputStream in = new BufferedInputStream(urlConnection);
I had also faced some app crashing experience because of handling error stream direclty.
Please do check always, It's a good practice.

Related

AsyncTask OutputStream fails for few devices

I have two AsyncTasks in my fragment. First to load (AsyncTask1) the initial set of data and then another (AsyncTask2) to load subsequent data as the app is scrolled down.
Both the tasks work perfectly in the emulator (Pixel, Nexus devices). As I scroll the second task loads new data seamlessly.
But when I run the app on Samsung Note 4, Samsung A5 and one other device then AsyncTask1 works correctly but the AsyncTask2 stops executing after the below line. I tried it on a Moto phone and it worked properly.
OutputStream outputStream1 = httpURLConnection.getOutputStream();
Below is my doInBackground method of AsyncTask2
#Override
protected String doInBackground(Integer... args) {
String arg_item_number = String.valueOf((args[0]*5));
np_page = args[0];
String arg_language;
if (args[1]==1){
arg_language = "en";
}else{
arg_language = "hi";
}
try {
URL url1 = new URL(url_get_next_posts);
HttpURLConnection httpURLConnection = (HttpURLConnection) url1.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream1 = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(outputStream1,"UTF-8"));
String data_string_language1 = URLEncoder.encode("item_number","UTF-8")+"="+URLEncoder.encode(arg_item_number,"UTF-8")
+"&"+URLEncoder.encode("selected_language","UTF-8")+"="+URLEncoder.encode(arg_language,"UTF-8");
bufferedWriter1.write(data_string_language1);
bufferedWriter1.flush();
bufferedWriter1.close();
outputStream1.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_NEXT_POST = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_NEXT_POST + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Error log
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/tag_item_count: 1
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#8bda7dd time:13839484
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.net.UnknownHostException: http:websitenname.com/script_url.php
W/System.err: at com.android.okhttp.internal.http.HttpEngine.createAddress(HttpEngine.java:1347)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:439)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
W/System.err: at com.app_name.android.app_name.PostTab$BackgroundNextPostsJSON.doInBackground(PostTab.java:374)
W/System.err: at com.app_name.android.app_name.PostTab$BackgroundNextPostsJSON.doInBackground(PostTab.java:347)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err: at java.lang.Thread.run(Thread.java:818)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
Can it be something related to the Android version running on the phone (Note 4 is running 6.0.1)? I have no clue what is wrong with the code as it actually works on emulator & Moto phone. Can the problem occur on other non-Samsung devices too?
In your stacktrace
http:websitenname.com/ is invalid URL due to it is missing double slash in the url scheme. Should be http://websitenname.com/ probably.
It worked on emulator and some devices probably because they have some undocumented improvements, and try to open even invalid URLs.

Can't read from buffered reader in android

I am trying to get data by using API. I get data in bufferedreader which contains multiple lines. But I am not able to extract that in a String. I do know that bufferedreader has data, i have checked by displaying it using multiple .readLine(); but the loop doesn't work.
protected String[][] doInBackground(Cursor[] cursors)
{
String list[][] = new String[cursors[0].getCount()][2];
//while(cursors[0].moveToNext())
{
String DATA="",temp;
String baseAddress="http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY";
String apiKey="J63P";
Uri Url = Uri.parse(baseAddress)
.buildUpon()
.appendQueryParameter("symbol","SBIN")
.appendQueryParameter("interval","1min")
.appendQueryParameter("apikey",apiKey)
.build();
Log.d("built URL",Url.toString());
try
{
url= new URL(Url.toString());
urlconnection= (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("GET");
urlconnection.connect();
InputStream inputStream = urlconnection.getInputStream();
if (inputStream==null)
{
Log.d("inputstream","empty");
return null;
}
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream));
while((temp = reader.readLine())!=null)
{
DATA.concat(temp);
}
Log.d("unedited",DATA);
}
catch(IOException e)
{
Log.e("createList", "Error in url ", e);
return null;
}
try {
String List = "Time Series (1min)";
JSONObject full = new JSONObject(DATA);
JSONArray permin = full.getJSONArray(List);
for (int i=0;i<permin.length();i++)
{
String open,high,low,close;
JSONObject current = permin.getJSONObject(i);
open = current.getString("1. open");
high = current.getString("2. high");
low = current.getString("3. low");
close = current.getString("4. close");
Log.d("Extracted ",open + " " + high + " " + low + " " + close +"\n");
}
}
catch (JSONException e)
{
Log.e("createList","Error in json",e);
}
}
return list;
}
and Log is:
04-24 14:34:52.009 3574-3619/lcukerd.com.stocknotifier D/built URL: http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=SBIN&interval=1min&apikey=J63P
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList: Error in json
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at lcukerd.com.stocknotifier.MainActivity$createList$override.doInBackground(MainActivity.java:123)
at lcukerd.com.stocknotifier.MainActivity$createList$override.access$dispatch(MainActivity.java)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:0)
at lcukerd.com.stocknotifier.MainActivity$createList.doInBackground(MainActivity.java:69)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Also, note that "Log" statement after inner while loop is also not working.
Pls, Help me Solve it.
You got exception in the Json data, it is very clear from the log, it says:
04-24 14:34:53.723 3574-3619/lcukerd.com.stocknotifier E/createList:
Error in json
Oh yeah:
Change this line:
DATA.concat(temp);
To
data = DATA.concat(temp);
Also in java it's better to write it this way:
data += temp;

Android API error / httpget NetworkOnMainThreadException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
This is my error message:
08-17 07:58:14.286 32620-32620/xxx.dk.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: xxx.dk.xxx, PID: 32620
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239)
at java.net.InetAddress.lookupHostByName(InetAddress.java:388)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at xxx.dk.xxx.DAL.JsonConnection.checkSecret(JsonConnection.java:42)
at xxx.dk.xxx.BLL.CheckCarrierData.checkSecret(CheckCarrierData.java:14)
at xxx.dk.xxx.GUI.Login.onClick(Login.java:49)
at android.view.View.performClick(View.java:4480)
at android.view.View$PerformClick.run(View.java:18686)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Im trying to use a httpGet method, which is working on API10, but it fails when im using it on an unit with 4.4.2 -> i need the support from API10 and up.
The code:
public class JsonConnection
{
private String secretJsonStr = null;
private String nameOfCarrier = "";
public String checkSecret(String secret)
{
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
final String QueryParam = "secret";
try
{
final String httpUrl = "***SOMEURL***?";
Uri builtUri = Uri.parse(httpUrl).buildUpon().
appendQueryParameter(QueryParam, secret.toString()).build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
{
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if (buffer.length() == 0)
{
// Stream was empty. No point in parsing.
return null;
}
secretJsonStr = buffer.toString();
} catch (IOException e)
{
Log.e("Login", "Error", e);
return null;
} finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
if (reader != null)
{
try
{
reader.close();
} catch (final IOException e)
{
Log.e("Login", "Error closing stream", e);
}
}
}
try
{
JSONObject secretJson = new JSONObject(secretJsonStr);
nameOfCarrier = getCarrierInfoFromJson(secretJson);
}
catch (JSONException e)
{
e.printStackTrace();
}
return nameOfCarrier;
}
private String getCarrierInfoFromJson(JSONObject secretJson)
throws JSONException
{
final String CARRIER_NAME = "Name";
String nameOfCarrier2 = secretJson.getString(CARRIER_NAME);
return nameOfCarrier2;
}
}
Due to some protection, i cannot show you the URL, but everything is working like a charm when running in API 10 2.3.6 units..
I though there where complete backwards compatibility on all android devices.
Hope you have the knowledge to help me on, I for sure cannot see how. :-(
Kindest regards
Rasmus
The problem is that the http requests are executed on the main thread (NetworkOnMainThreadException), so you need to move the calls into a Thread. More info here.
update: actually, possible duplicate of this.
As error say you can't execute an HTTP connection on the MainThread that would froze the screen. which is not appropriate.
You can get that permission as the following:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But, this is not a good practice. you must run the http connection on a background thread and display a loading msg to the user.
new Thread(new Runnable() {
#Override
public void run() {
// code goes here ...
}
}).start();
As other answers are suggesting, you are getting this error because you are running network operation on main thread. I would suggest to use AsyncTask.
This link shows you structure of AsyncTask.
To call the AsyncTask, use
//getData() is name of class
new getData().execute();
More reference on Android Developer site.

Android Unit Tests

I am trying to write a AndroidTestCase for one of my classes that make connection to a server and parse the returned JSONObject. When I test the functionality in the UI, the file works fine and the correct information are parsed and displayed. When I input the URL into my browser, I get the correct JSONObject back. However, when I try to get the JSONObject through a AndroidTestCase and simply verifying that it's not null, I get IOException when it tries to get the corresponding JSONObject for an url. I verified that the url it's using is correct. Here's the stack trace.
java.net.UnknownHostException: api.penncoursereview.com
at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
at java.net.InetAddress.getAllByName(InetAddress.java:256)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
at edu.upenn.cis.cis350.backend.Parser.retrieveJSONObject(Parser.java:34)
at edu.upenn.cis.cis350.test.ParserTest.test_retrieveJSONObject(ParserTest.java:22)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
Any idea why the code works in simulator but not in test?
Thanks in advance for the help!
edit:
Here is the relevant method:
public JSONObject retrieveJSONObject(String path){
try{
URL url = new URL(path);
Log.w("Parser: retrieveJSONObject", "url=" + url);
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Length",builder.toString());
return new JSONObject(builder.toString());
}
catch(IOException e) {
Log.w("Parser: retrieveJSONObject", "IOException: Bad Url");
e.printStackTrace();
return null;
} catch (JSONException e) {
Log.w("Parser: retrieveJSONObject", "JSONException: mis-formatted JSON");
e.printStackTrace();
return null;
}
}
Line 34 is the line initializing the BufferedReader.
I guess what you are missing is the INTERNET permission.
Considering that your method is defined static in Utils class, the following test works.
public void testRetrieveJSONObjectWithUrl() {
final String url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
assertNotNull(Utils.retrieveJSONObject(url));
}

HTTP Request fail

I have to get an HTTP request like this:
http://www.aroundertouch.com/queriesandroid1dot0/project/idProjet/45.484171;;9.050393;;Rotondi Group S.R.L. - Costruzione Macchine Abbigliamento/iphone/354781043339495/lang/en_US
With this code:
url = new URL(query);
Log.d(TAG,url.toString());
connection = url.openConnection();
httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
// HTTP status okay
if (responseCode == HttpURLConnection.HTTP_OK) {
// preparo stream
in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(in);
}
// HTTP status fail
else{
throw new Exception("responseCode != 200 OK in "+query);
}
in.close();
httpConnection.disconnect();
_ret = parseXML(dom);
I meet this exception and I suspect that it is caused by an not encoded URL, how can I encode my URL? It isn't automatically encoded by HTTPURLConnection?
Excpetion:
D/dalvikvm(10100): GC freed 3447 objects / 513168 bytes in 47ms
W/System.err(10100): org.xml.sax.SAXParseException: Unexpected end of document
W/System.err(10100): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:129)
W/System.err(10100): at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:157)
W/System.err(10100): at granet.arounder.webservice.ThreadDatiCard.doInBackground(ThreadDatiCard.java:76)
W/System.err(10100): at granet.arounder.webservice.ThreadDatiCard.doInBackground(ThreadDatiCard.java:1)
W/System.err(10100): at android.os.AsyncTask$2.call(AsyncTask.java:185)
W/System.err(10100): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
W/System.err(10100): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
W/System.err(10100): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
W/System.err(10100): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
W/System.err(10100): at java.lang.Thread.run(Thread.java:1096)
Thanks a lot.
Yes the data in your URL contains spaces which is bad and probably causing your request to not return what you are expecting to parse, use the built in urlencoder.
http://developer.android.com/reference/java/net/URLEncoder.html

Categories

Resources