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;
}
Related
In my app am parsing json with HttpPost like this
`
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpContext localContext = new BasicHttpContext();
String url="http://ashishva.comxa.com/getdata_shoplistl_f.php?route="+sroute+"&shop_type="+sshoptype;
HttpPost httpGet = new HttpPost(url);
HttpResponse response = httpClient.execute(httpGet, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()`
My manifest file is set correctly for internet access
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I am getting the json in my browser, but getting the results in my android phone and emulator SOMETIMES ONLY. Why is this happening so? Why getting sometimes and not getting later.
While am not getting any data , am getting the exception
"java.net.UnknownHostException: Unable to resolve host "ashishva.comxa.com": No address associated with hostname"
Actually i found out the solution. This line
HttpPost httpGet = new HttpPost(url);
had to be replaced with HttpGet as
HttpGet httpGet = new HttpGet(url);
The best one I have found is in android developer training below is the link
http://developer.android.com/training/basics/network-ops/connecting.html
Connect and Download Data
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
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.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
Convert the InputStream to a String
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
I'm trying to send notification for both Android & iOS using non-Latin charset.
I notice when I send message from Android to iOS using non-Latin charset, message displayed on iPhone as "????", since the Java server side for iOS and Android are the same, I assume the problem is how I send the request from Android handset, notice message from iOS to iOS works fine.
below is the code that I'm using to open network connection and sending the request, please, let me know if it's OK.
byte[] bytes = body.getBytes(/*"UTF-16"*//*"ISO-8859-1"*/"UTF-8");
HttpURLConnection conn = null;
StringBuilder stringBuilder = new StringBuilder();
try {
conn = (HttpURLConnection) url.openConnection();//conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
Log.d("send message", "Coud Send Message, No Internet Connection Avilable.");
throw new IOException("Post failed with error code " + status);
}
InputStream in = new BufferedInputStream(conn.getInputStream());
// readStream(in);
int b;
while ((b = in.read()) != -1) {
stringBuilder.append((char) b);
}
check below code it works for me, i have also same issue,
to get Data from server,
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2,
HTTP.UTF_8));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
return is;
hope it may help you.
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!
I Use BufferedInputStream For HTTP POST/GET
But I Get Some Error the Below
java.io.FileNotFoundException: http://XX.XX.XX.XX/WebWS/data.aspx
Transport endpoint is not connected
Why Get This Error. My Code is Below
URL url = new URL(glob.postUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
try {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Language", "TR");
httpConn.setConnectTimeout(12000);
Iterator<String> reqProps = hMap.keySet().iterator();
while (reqProps.hasNext()) {
String key = reqProps.next();
String value = hMap.get(key);
httpConn.addRequestProperty(key, value);
}
InputStream in = new BufferedInputStream(httpConn.getInputStream());
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
httpConn.disconnect();
Thanks.
Is there any reason you're not using HttpClient?
You can replace your code with something like:
HttpContext httpContext = new BasicHttpContext();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String page = EntityUtils.toString(entity);
You can setup the HttpClient with ClientConnectionManager and HttpParams for security and various http parameters for the client at initialisation (plenty of examples around if you search on class names).
HttpURLConnectionImpl.getInputStream() is known to throw a FileNotFoundException if the HTTP response status code is 400 or higher, i.e. for any error condition on the server side. You should check what the status code really is in order to obtain suitable debug information.
However, I second Mark Fisher's suggestion about using HttpClient, which AFAIK is the preferred way of working with HTTP on Android.
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()));