Reading long string from socket in Android issue - android

I am getting long string data from server via socket and there is reading issue .
Data is around 10 MB .
private String createSocketConnection() throws IOException {
String result = "";
{
String host = ServiceUrlManager.socketIP;
int port = ServiceUrlManager.socketPort;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
socket.setSoTimeout(timeOut);
Log.d(TAG, ":::::Socket Connection " + socket.isConnected());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.write(createMSG());
dataOutputStream.write(sockecData);
dataOutputStream.flush();
//Read data from server connection
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
for(int s; (s=inputStream.read(buffer)) != -1; )
{
baos.write(buffer, 0, s);
}
String data = ISOUtil.hexString(baos.toByteArray());
result = data.substring(0, baos.toByteArray().length); // response message
Log.d(TAG, "::::Response " + result);
}
return result;
}

BufferedReader in =
new BufferedReader(
new InputStreamReader(inputStream.getInputStream()));
StringBuilder sb= new StringBuilder();
while(br.readLine!=null){
sb.append(br.readLine());
}

Related

ServerResponse 404 while uploading image to server

I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.
Here is my code
class SaveFile extends AsyncTask<String,String,String>
{
FileInputStream fileInputStream;
HttpURLConnection connection;
URL url;
DataOutputStream outputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedImagePath);
//selectedImagePath = path of Image in phonememory
#Override
protected String doInBackground(String... params)
{
Log.v(TAG,"Image path is " + selectedImagePath);
try
{
fileInputStream = new FileInputStream(selectedFile);
url = new URL(SEND_IMAGE);
connection= (HttpURLConnection)url.openConnection();
Log.v(TAG,"connection established");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
//connection.setRequestProperty("image1",selectedImagePath);
//connection.setRequestProperty("user_id","1");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--*****\r\n");
outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
outputStream.writeBytes("\r\n");
//outputStream.writeBytes("--*****\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer,0,bufferSize);
while (bytesRead>0)
{
outputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****--\r\n");
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Log.v(TAG,"Response is " +sb.toString());
}
Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
Log.v("UploadImage"," " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
but I am getting serverResponse 404
I tried solutions like Uploading Image to Server - Android but not worked.
I searched a lot.but couldnt find solution
Please Help!!
I want to say that this maybe a server error. 404 in most cases is an error that says, "you have used wrong url". Check whether this url is correct.try to upload your data in your browser.

How to read variable amount of json data from url?

I am using the following code to read json data from url , but it has fixed length of 500 for the json data. How can I ensure that all the data(variable length) is always read.
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();
}
}
}
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);
}
Thanks.
Reference
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + newLine);
}
String result = sb.toString();
byte[] data = new byte[1024];
int bytesRead = inputstream.read(data);
while(bytesRead != -1) {
doSomethingWithData(data, bytesRead);
bytesRead = inputstream.read(data);
}

Load local HTML file(from assets) to a String

How can I load a local html file(from assets folder) to a String?
I tried this code but the result is only "?????...".
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
System.out.println(str);
thanks for any help!
You are not reading the whole file. Try this:
StringBuilder builder = new StringBuilder();
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1) {
builder.append(new String(buffer));
}
is.close();
String str = builder.toString();
try this......
File file = new File("file:///android_asset/yuor_file.html");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String linewise = br.readLine();
while(linewise != null) {
sb.append(linewise );
sb.append("\n");
linewise = br.readLine();
}
//now data in sb

How to read from .txt file

i am trying to read the text from a file which is present on server, this file containing the text "hello world" ,now i want to write this text on TextView . i have imported all required packages . thanks in advance
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
try {
URL updateURL = new URL("http://--------------------/foldername/hello.txt");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
final String s = new String(baf.toByteArray());
((TextView)tv).setText(s);
} catch (Exception e) {
}
};
try this function ....
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
try this code
URL url = new URL(urlpath);
BufferedInputStream bis = new BufferedInputStream((url.openStream()));
DataInputStream dis = new DataInputStream(bis);
String full = "";
String line;
while ((line=dis.readLine())!=null) {
full +=line;
}
bis.close();
dis.close();
((TextView)tv).setText(full);

FILE TRANSFER in android

this is regarding android instant messenger. im trying to send a file, and this is how i send it :
#Override
public boolean sendFile(String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("SO sendFILE","null");
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [1024];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
this is how i receive connection and seperate text from file (i concatenate "text" to the output stream for the text)
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=clientSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
and this is how i finally receive the file in a service called imService :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead = 0;
System.out.println("imService fileReceive" + bytesRead);
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
System.out.println("imService fileReceive" + bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
right where i receive the file connection and forward the inputstream IS to the file receive method, i see that its getting the bytes but once filereceived is called it isnt receving any bytes.
it uses tcp/ip.
ok, try it on your method
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException
{
string result;
FileOutputStream fos = null;
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null)
{
// result = convertStreamToString(is);
// result = result.replace("\n", "");
// Log.e("InputStream output",result);
//IOUtils.copy(is,fos);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
fos.write(buffer, 0, length);
}
// Close the streams
fos.flush();
fos.close();
is.close();
}
}
/* public static String convertStreamToString(InputStream is)
throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
*/
EDIT: make other stuff in fileReceived method as comment.. just paste my suggested code.
EDIT: its a IOUtils from apache use it..

Categories

Resources