HttpURLConnection mobile network - android

I'm having trouble to connect to a webservice through HttpURLConnection when using 3g (any mobile network). I don't know exactly the problem because when it's on the wifi, it works perfectly. When I check for the errorStream, it says that the buffer length is unknown. Why does it happen only through 3g?
My code is:
if (method_type == 0) {
param = url[0].concat("?identificacao=" + postDataParam.get("identificacao") + "&senha=" + postDataParam.get("senha"));
System.out.println(param);
try{
URL link = new URL(param);
HttpURLConnection e = (HttpURLConnection)link.openConnection();
e.setReadTimeout(15000);
e.setConnectTimeout(15000);
e.setRequestMethod("GET");
e.setRequestProperty("User-Agent", "");
e.setRequestProperty("Authorization", "Basic " + base64CredenciaisCodificadas);
BufferedReader in = new BufferedReader(
new InputStreamReader(e.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
resposta = response.toString();
globalResposta = resposta;
senhaCorreta = Boolean.parseBoolean(separarDados(globalResposta, 0).replace("\"", ""));
} catch(Exception e){
}
}
Before you all ask, I tried changing the User-Agent to Mozilla, AppleWebKit and this stuff. I have also set the permission to access the internet at the manifest.

Related

Why am I getting 500 response code on passing wrong email or password to service in android?

I have been running into a very strange problem. I am trying to implement log in service in my app. When I pass right email and password service returns response as expected(means no error comes) but when I delibrately pass wrong email or password geInputStream() method throws FileNotFoundException. I don't know what is the reason behind this.Further more, before calling getInputStream() method i checked status code as well(this is the case when I am passing wrong email and password intentionally).The status code was 500. I checked for 500 and that was internal server error. My question is why is that so? I mean when intentionally passing wrong email or password why internal server occurred? One more thing I would like to mention that I have checked the same service on post man it is working fine as expected. If i pass wrong email or password postman returns the expected error. Below is the code I am using
private String invokeWebservice() {
String data = null;
HttpURLConnection conn = null;
BufferedReader in = null;
try {
String webservice = Constants.BASE_URL + serviceName;
LogUtility.debugLog("webservice just called "+ webservice);
URL url = new URL(webservice);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setUseCaches(false);
if (isPost) {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
if (jsonObject != null)
writer.write(jsonObject.toString());
writer.close();
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null)
sb.append(l + nl);
in.close();
data = sb.toString();
return data;
} catch (Exception e) {
LogUtility.errorLog("exception while calling web service");
} finally {
try {
if (conn != null)
conn.disconnect();
if (in != null)
in.close();
} catch (Exception ex) {
// LogUtility.errorLogWithException(ex, ex.getMessage());
}
}
return data;
}
Any help?
After spending some time now I was able to solve my problem.Posting my answer for others. Passing wrong email and password to the service was right and server was consuming those parameters as well and because there was an error(because email and password) that is why it was returning 500 code. So, I checked for status code if it was 200 then I used getInputStream() method and else i called getErrorStream() method. By this way i got the stream that has property for error(this property contains error detail). Below is the code i used
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
Hope it helps other as well.

different outcome in different phones

I have 2 phones:
lg g3 that i bought from China
and lg g3 that i bought from Israel
i build an android app that gets a response from web according to a keysearch(key search can be in any language:russian,hebrew, arabic, english etc.)
In english, both phones work great.
But when i use non-english langauge(all above, didn't try chinese) the Israel phone still works great but the China phone not.
When i debug the program in the China phone i saw that the keysearch (in non english langaage) when i get the reponse is in question marks. but in the Isreal phone it's works great, so i tried all kinds of encoding, but nothing seems to work.
here's the piece of the code that have the problem:
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL("https://www.example.com/results?search_query="+keyword);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append('\r');
}
m_htmlDoc = response.toString();
} catch (Exception e) {
e.printStackTrace();
m_htmlDoc = null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
the question is: do i need to change something in the code so the China phone will accept other langauges (not just english)? if so, it would be great if someone can direct me to the answer. if not, so maybe i need to change settings on the phone? both phones has the same OS langauge (hebrew)
Thank you all.
so the utf-8 was correct and i didn't need tochange any local langauge on the phone all i needed is to encode the keysearch (URLEncoder.encode(keyword, "UTF-8")).
this is the complete answer:
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL("https://www.example.com/results?search_query=" + URLEncoder.encode(keyword, "UTF-8"));
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
response.append('\r');
}
m_htmlDoc = response.toString();
} catch (Exception e) {
e.printStackTrace();
m_htmlDoc = null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
Thank you all for the help.

Issues with http request in Android

I am new to this website, so if i do something wrong please tell me.
I am trying to establish a connection between my node.js server and my android app. For example, I'm trying to connect a page called showWithAuth, where i need to authenticate with digest stategy.
For this purpose i use Authenticator :
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication (username, password.toCharArray());
// System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
}
});
My real issue is when i try to establish the connection :
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
/*connection.setInstanceFollowRedirects(false);
int status = connection.getResponseCode();
InputStream is;
if (status >= 400 && status <= 499) {
throw new Exception("Bad authentication status: " + status); //provide a more meaningful exception message
}
else
{*/
//connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
//connection.setRequestProperty("Accept", "*/*");
/*is = connection.getInputStream();
}
byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
builder.append(new String(buffer, 0, readCount));
}
String response = builder.toString();
System.out.println(response);*/
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The issue i have is a filenotfoundexception, at this line :.getInputStream()));
The response of the server is a 401 : bad authentication status
I saw some people having the same issue i deal with, but i tried every single solution without getting anything better.
If you could help me to get what i do wrong ! Thank you !
PS: the commented code was also tried.
PS2: sorry for being so long.
Edit: Just to say also that this code is working on Netbeans with Java only, but not in Android Studio
Please try by adding the
<uses-permission android:name="android.permission.INTERNET" />
To your AndroidManifest.xml file, this may solve your problem.

how I get the html source with utf-8 format?

I write this code to get html source from a site.
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "aranan="+et.getText();
try
{
url = new URL("http://www.fragmanfan.com/arama.asp");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
browser.loadDataWithBaseURL(null, response,"text/html", "UTF-8", null);
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}
});
But there is a one problem.It is : response (the variable that have html source) is not utf-8 format.
How I can fix this?
Thanks.
.
.
.
InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"ISO-8859-9");
.
.
.
Since your response seems to be your HTML webpage in a single String, you should make sure that the head tag of your page cointains the label that defines the codification.. if not you can append it yourself to your StringBuilder.
Here is how you can do it:
final StringBuilder sb =
new StringBuilder("<html><head>"+ "<meta http-equiv=\"content-type\"content=\"text/html;charset=utf-8\" />"+ "</head><body>");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
sb.append(response);
sb.append("</body></html>");
and then you can properly load your HTML to your webview / browser. (this worked for me so I know for sure that it actually works =] )
p.d. make sure to accept the answer that properly answer your question so people keep answering your future questions.
https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work

How do I send a request to different page on the logged site

First, I want to connect to the site.
After, I want to get a data from different page with this connection
sample:
1- connect to http://site.com/Login with user pass
2- get a secret data from http://site.com/Secret
How do I do this, pleas help me...
OutputStreamWriter request = null;
url = new URL("http://site.com/Login");
String response = null;
EditText user = (EditText)this.findViewById(R.id.user);
EditText pass = (EditText)this.findViewById(R.id.pass);
String parameters ;
try {
System.setProperty("http.keepAlive", "true");
url = new URL("http://site.com/Home/Login");
httppost = (HttpURLConnection) url.openConnection();
httppost.setDoInput(true);
httppost.setDoOutput(true);
httppost.setRequestMethod("POST");
httppost.setRequestProperty("User-Agent", "Mozilla/5.0 Linux U Android 2.3.3 tr-tr HTC_DesireHD_A9191 Build/GRI40 AppleWebKit/533.1 KHTML, like Gecko Version/4.0 Mobile Safari/533.1");
httppost.setRequestProperty("Accept_Language", "en-US");
httppost.setRequestProperty("Connection", "Keep-Alive");
httppost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
request = new OutputStreamWriter(httppost.getOutputStream());
parameters = "username="+user.getText()+"&password="+pass.getText();
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(httppost.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
Toast.makeText(this,response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
You should use WebView and sorry but you can not get the webview content.
If you own the server-side code and you want to access from java then you should use an access token for more secure connection and get data by using JSON or XML. Or there is a much more secure connection type which is OAuth2.
If you don't own server, you should show the http://site.com/Login url in webview. When the user logins than you have cookie in your webview. You can use CookieManager http://developer.android.com/reference/android/webkit/CookieManager.html and send the data by using this cookie and get the result. This method is not easy and can differentiate according to server-side implementation.

Categories

Resources