MalformedURLException: Protocol not found. RSS feeds on Android - android

I'm using the code to parse RSS from this link IBM - Working with XML on Android...and I have little problem with the URL's. If I use this URL:
static String feedUrl = "http://clarin.feedsportal.com/c/33088/f/577681/index.rss";
It works right, but if I use this URL:
static String feedUrl = "http://www.myworkingdomain.com/api/?m=getFeed&secID=163&lat=0&lng=0&rd=0&d=1";
It gives me:
07-07 19:41:30.134: E/AndroidNews(5454): java.lang.RuntimeException: java.net.MalformedURLException: Protocol not found:
I've already tried hints from other answers...but none of them help me out...
Any other solution?
Thanks for your help!

Seeing your feedUrl, I assume that you want to do an HTTP GET request with parameters. I had a lot of trouble with that too, until I started using a StringBuilder and an HttpClient.
Here's some code, without exception catching:
SAXParserFactory mySAXParserFactory = SAXParserFactory
.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
HttpClient httpClient = new DefaultHttpClient();
StringBuilder uriBuilder = new StringBuilder(
"http://myworkingdomain.com/api/");
uriBuilder.append("?m=getFeed");
uriBuilder.append("&secID=163");
[...]
HttpGet request = new HttpGet(uriBuilder.toString());
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
Log.e("HTTP CLIENT", ostream.toString());
}
InputStream content = response.getEntity().getContent();
// Process feed
InputSource myInputSource = new InputSource(content);
myInputSource.setEncoding("UTF-8");
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
content.close();
Hope this helps!

Related

Passing cookie with an HTTT GET

I am trying to get a list of user subreddits via the reddit api. Currently I am able to do a post for login which returns a cookie and modhash. Those are the parameters I'm passing to my method below. However each time I call the function I get an empty response:
"{}"
How can I pass a cookie and modhash via HTTPGET to get a valid response?
public void getUserSubreddits(String[] loginInfo){
HttpClient client = new DefaultHttpClient();
URL url = null;
try {
url = new URL("http://www.reddit.com/subreddits/mine/.json?limit=100");
HttpGet httpGet = new HttpGet(String.valueOf(url));
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httpGet.addHeader("cookie", loginInfo[1]);
httpGet.addHeader("modhash", loginInfo[0]);
HttpResponse response = client.execute(httpGet);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
Log.d(TAG,total.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
It was a simple mistake. To anyone in the future trying this I solved the problem by using Chrome to inspect the headers of an active session on http://www.reddit.com/subreddits/mine/.json?limit=100 url and found that the cookie header started with:
reddit_session
So I removed the modhash changed the my header parameter to read:
httpGet.addHeader("cookie", "reddit_session="+loginInfo[1]+";");
With this I got a valid response.

OKHTTP response XMLPullParser

I am transitioning to OKHttp and i am using SAXParser in my project. How can i parse the OKHttp response to SAXParser? or how else can I parse XML using the library.
initially this was how I was doing it:
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
SAXParserFactory factory1 = SAXParserFactory.newInstance();
SAXParser parser = factory1.newSAXParser();
FormHandler handler = new FormHandler();
parser.parse(inputStream, handler);
But with OKHTTP, how can i pass Response response = client.newCall(request).execute() to the XML parser?
You might try this :
// 1. get a http response
Response response = client.newCall(request).execute();
// 2. construct a string from the response
String xmlstring = response.body().string();
// 3. construct an InputSource from the string
InputSource inputSource = new InputSource(new StringReader(xmlstring));
// 4. start parsing with SAXParser and handler object
// ( both must have been created before )
parser.parse(inputSource,handler);
PS : in your question you mention XMLPullParser, in your code you're actually using a SAXParser. However, if you have the xml string on your hands, you should do fine with both ways.

Android URLConnection POST instead of GET

I have an app that needs to POST several values to a URL, and return the XML response so that it can be parsed. Currently, the request is sending the values via the URL. Below is my current working code, but I'm not able to find any information on the android developers site about POST with URLConnection. Is it possible? Any examples? thank you in advance for any help!
String url = "http://www.mywebsite.com/xml/page.cfm";
StringBuilder sb = new StringBuilder(url);
sb.append("?id=" + id);
URLConnection conn = new URL(sb.toString()).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLDataHandler h = new XMLDataHandler();
xr.setContentHandler(h);
xr.parse(new InputSource(conn.getInputStream()));
XMLData = XMLDataHandler.XMLData;
Looks like you should use HttpURLConnection.
This post may help you:
How to add parameters to HttpURLConnection using POST

SAX Parser Doesn't Read Stream from HttpsURLConection.getInputStream()

yet another tiny roadblock in my Android learning progress.
here's my code:
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
byte[] encodedPassword = (user + ":" + pass).getBytes();
String auth = "Basic " + Base64.encodeToString(encodedPassword, false);
con.setRequestProperty("Authorization", auth);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","text/xml");
con.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
con.setRequestProperty("Connection", "close");
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setAllowUserInteraction(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int statusCode = ((HttpURLConnection) con).getResponseCode();
Log.d(TAG, "Response Code = " + statusCode + " Content-Length = " + con.getContentLength());
I got a response code = 200 and content length = 2593 so i know i have access to the file
DataInputStream re = new DataInputStream(con.getInputStream());
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLmyHandler myHandler = new XMLmyHandler();
xr.setContentHandler(myHandler);
xr.parse(new InputSource(re));
the file is well formatted, i copied it to a local non secure http server and it worked perfectly.
Sadly, when i try to do the same from secure http it wouldn't work.
also, with my non-secure http successful attempts i use HttpClient to get a stream and not this method.
however, my attempts of using HttpClient with secure http failed miserably.
I'd prefer to keep this method, if you know any way to extract a stream from my "con" that works with SAX please let me know!!! thanks ahead on any help i get.
after trial and error i found a dirty fix for this problem
i removed the data output stream then the data input stream worked fine
//DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.writeBytes(urlParameters);
//wr.flush();
//wr.close();
try {
StringBuffer inLine = new StringBuffer();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyXMLHandler myExampleHandler = new MyXMLHandler();
xr.setContentHandler(myExampleHandler);
InputStream in = this.getResources().openRawResource(
R.raw.myxmlfile);
xr.parse(new InputSource(in));
MyXMLHandler parsedExampleDataSet = myExampleHandler;
inLine.append(parsedExampleDataSet.toString());
in.close();
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
Log.i(TAG, e.toString());
}
here is compete code available have a look Android XML Parsing Tutorial - Using SAXParser
Happy coding :):) :Pragna
Use following code,
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLmyHandler myHandler = new XMLmyHandler();
xr.setContentHandler(myHandler);
xr.parse(getInInputStreamFromURL(ur url here.....));
public AndroidHttpClient getClient(String userAgent) {
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
// Default connection and socket timeout of 20 seconds. Tweak to taste.
HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
HttpConnectionParams.setSoTimeout(params, 20 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Don't handle redirects -- return them to the caller. Our code
// often wants to re-POST after a redirect, which we must do ourselves.
HttpClientParams.setRedirecting(params, false);
// Set the specified user agent and register standard protocols.
HttpProtocolParams.setUserAgent(params, userAgent);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
schemeRegistry.register(new Scheme("https", socketFactory, 443));
ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
// We use a factory method to modify superclass initialization
// parameters without the funny call-a-static-method dance.
return new AndroidHttpClient(manager, params);
}
public InputStream getInInputStreamFromURL(String url) {
InputStream inputStream = null;
AndroidHttpClient httpClient = null;
try {
httpClient = getClient("Ramindu");
// Example send http request
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
inputStream = response.getEntity().getContent();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, "CAUGHT EXCEPTION : " + e);
}
return inputStream;
}

do not understand xml parsing code

the following code is for xml parsing.
try
{
HttpEntity entity = response.getEntity();
final InputStream in = entity.getContent();
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
final XmlHandler handler = new XmlHandler();
Reader reader = new InputStreamReader(in, "UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
parser.parse(is, handler);
//TODO: get the data from your handler
}
catch (final Exception e)
{
Log.e("ParseError", "Error parsing xml", e);
}
over here where do i pass the url.
also the response object in the line
response.getEntity() is an object of HttpResponse()?
thank you in advance.
The code you show is the processing after the url connection has been opened, and the result has been obtained. At this point there is no more url to pass.
response is the HttpResponse.
I think you can do something like this:
Url url = new URL("http:// [and so on]");
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(url.openStream()));

Categories

Resources