do in background split not working - android

please i want to know what is wrong with this code, if i try to split, it just crashes my app, but without the split line of code my app runs sucessfully and returns a response from my server with the delimeter "|" here is the code:
protected String doInBackground(String... params) {
String type= params[0];
String login_url="somelink.com/somelink.php";
if(type.equals("login")){
try {
String username= params[1];
String password= params[2];
URL url= new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data=URLEncoder.encode("n", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data+="&" + URLEncoder.encode("p", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
String[] words=result.split("\\|");
StringBuilder ch=new StringBuilder();
ch.append(words[0]);
String check=ch.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return check;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

The only obvious thing I can see is that you are probably accessing an element that does not exist. This line:
ch.append(words[0]);
It's possible that the length of the words array, in some cases, can be zero (e.g., because line is empty, etc.), and you are trying to access a non-existent element.
All you have to do is add if statement to check if you have a non-empty array before you do words[0].

Related

NOt able to read a InputStream

InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line ="";
while((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
message shows nothing, result is not given
The problem is that your are not appending the line into your result.
Make result variable String Buffer and use append function to do so then return the string from string buffer using toString function

Android HttpURLConnection image uploads but file not recognized as JPEG

I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>

How to connect Android on external host (not localhost)

I decided to connect to an external host my app but don't work. How can i do?
this is an exemple:
String login_url = "http://***.**.**.**/fileman/**/register.php";
// String login_url = "http://10.0.2.2/code/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
ritorno = "Registration Success...";
return ritorno;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
with localhost work, but when i use my url don't work.. (if i use my url on google adress he work)
what is wrong?
Are you supposed to be using login_url rather than reg_url in URL url = new URL(reg_url)? I think reg_url was initialized with something else.

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);
}

read text file returned by URL

This URL return & open text file directly, i just want to read its content how can i do it
http://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=en&tl=gu&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=this+is+translate+demo
i have tried
public static String translate(String sl, String tl, String text) throws IOException{
// fetch
URL url = new URL("https://translate.google.com.tw/translate_a/t?client=t&hl=en&sl=" +
sl + "&tl=" + tl + "&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q=" +
URLEncoder.encode(text, "UTF-8"));
Log.d("URL", ":: "+url);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("User-Agent", "Something Else");
Log.d("URL", ":: After opening Connection");
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
Log.d("URL", ":: br "+br);
String result = br.readLine();
br.close();
// parse
Log.d("URL", ":: "+result);
result = result.substring(2, result.indexOf("]]") + 1);
StringBuilder sb = new StringBuilder();
String[] splits = result.split("(?<!\\\\)\"");
for(int i = 1; i < splits.length; i += 8)
sb.append(splits[i]);
return sb.toString().replace("\\n", "\n").replaceAll("\\\\(.)", "$1");
}
If Your Url directly open's the Text File then this code reads the TextFile and print's also as follows:
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Categories

Resources