Cant get String out of Base64 encoded ByteArrayDataSource - java

I have a String converted with org.apache.axis2.databinding.utils.ConverterUtil to a Base64Binary (ByteArrayDataSource inside a DataHandler).
When I try to convert it back to the string, it doestn work. I cant figure out why. What am I missing?
Here`s the code:
#Test
public void testBase64() {
DataHandler test = ConverterUtil.convertToBase64Binary("TEST");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(test.getDataSource().getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String result = new String(Base64.decode(sb.toString()));
} catch (IOException e) {
e.printStackTrace();
}
As you can see.. result string is empty..
I hope someone can help me with this.
Thanks

Related

Not able to convert String to InputStream for parsing XML

I am trying to parse XML code from a server to use in Android. The URL is working, and up to SB I get the XML. When converting String to InputStream i get this in the logcat : java.io.ByteArrayInputStream#9e7122d
any help ?
thanks !
private InputStream downloadUrl(String urlString) throws IOException {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(60000);
con.setReadTimeout(60000);
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
InputStream stream = IOUtils.toInputStream(sb, "UTF-8");
Log.d(TAG, "SB " + sb);
Log.d(TAG, "STREAM" + stream);
return stream;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
There is no problem here to solve. The ByteArrayInputStream#9e7122d thing is just what ByteArrayInputStream.toString() returns.
BUT Why are you doing this? Loading the entire URL into memory adds latency and wastes space, and won't fit beyond a certain size. There is no benefit. Just return con.getInputStream().

How to change address in url (http://localhost:8080/HELLO_WORLD) in NanoHttpd

My query is how to change how to change address in URL (http://localhost:8080/HELLO_WORLD). I change HELLO_WORLD to desire word.
#Override
public Response serve(IHTTPSession session) {
String answer = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(appContext.getAssets().open("block.html")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
answer += mLine;
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
Log.d("BABAR", "EXception occured in serve()");
}
}
}
return newFixedLengthResponse(answer);
}
please suggest me how to change
I donĀ“t know if this is what you want, but you can try.
You have to follow the steps:
1- Create a local to store your server files;
2-Then change the response in the class that is implementing the NanoHttp server to something like this:
#Override
public Response serve(IHTTPSession session) {
String answer = "";
try{
FileReader filereader = new FileReader(contextoMain.local(localyourstorethefiles)+"/yourfolder/yourfile.html");
BufferedReader reader = new BufferedReader(filereader);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
}catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return newFixedLengthResponse(answer);
}
3 - Then, call the localhost:8080 without putting the 8080/yourfolder/yourfile

How to pass and read string from android to sql using JSON

Previously, i can access the string from php remotely. I find it difficult at first but AsyncTask did the work for me. Now, i can access the result of the query from php to sql server. But I would like to pass a string from my java class to php and as I googled some information, i saw some JSON post and get codes but i can't clearly understand them. Here's my code:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
The string is contained in "sb.toString()". Now how would I add a JSON something in my code to send string from java to php, and also get the result string from php to java as well. Thanks in advance for any help.
If you receive response as JSON format from server, make the json string to JSONObject first. And then read the json data for your use.
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
Your code already contains the answer of your question. After make url connection, just add parameter for sending your data to server with OutputStreamWriter as like you did for receive the response with InpustStreamReader.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here

java - Socket Stream

i want to get text from stream . but i dont get it correctly .
Everything works good , but i only need to know how to get PrintWriter into string .
i tried to convert PrintWriter with the function .ToString() but it doesnt work correctly , is print differen string .
Java :
private ServerSocket Server_Socket;
private static final int CLIENTRPORT = 5000;
Socket socket = null;
class Connect_To_Client implements Runnable
{
#Override
public void run()
{
try
{
Server_Socket = new ServerSocket(CLIENTRPORT);
socket = Server_Socket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public BufferedReader input;
public String Get_Message_From_Server()
{
PrintWriter out = null;
String out_string = "";
try
{
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(input);
}
catch (IOException e)
{
e.printStackTrace();
}
return(out_string);//the text - problem
}
To read from a buffered reader do something like this
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
return sb.toString();

Reading HttpURLConnection

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.
I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.
Thanks in advance!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
There are a bunch of things wrong with the code I posted in the question. Here is a working example:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It appears you are not connecting your HTTPUrlClient try con.connect()

Categories