about android sending get request - android

Here I have a problem with getting request in Android.
I have run server program using webapp2 on my PC and I succeeded in sending request from itself to the server program.
However, when I tried to send request from my phone, it seems the program always jump the catch(Exception e) part. The three Log.e() works fine since I could see all of them in the log records. Can anyone tell me what might go wrong here? Is it the fire wall that my PC used to block the request? Thanks in advance.
PS: the variable resultString is the result I get from voice recognition.
try{
StringBuilder buf = new StringBuilder("http://192.168.1.100:9080/");
buf.append("?");
buf.append("content1="+URLEncoder.encode(resultString,"UTF-8"));
//buf.append(resultString);
//Toast.makeText(MainActivity.this, buf, Toast.LENGTH_SHORT).show();
URL url = new URL(buf.toString());
Log.e("check1","url_transformation works ok");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
Log.e("check2","open connection works ok");
conn.setRequestMethod("GET");
Log.e("check3","set get works ok");
if(conn.getResponseCode()==200){
Log.e("check4","get works");
Toast.makeText(MainActivity.this, "GET works", Toast.LENGTH_SHORT).show();
}
else
{
Log.e("check5","get fails");
Toast.makeText(MainActivity.this, "GET fails", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Toast.makeText(MainActivity.this, "other problems occur", Toast.LENGTH_SHORT).show();
}
03-05 20:47:19.486: W/System.err(16066): android.os.NetworkOnMainThreadException
03-05 20:47:19.486: W/System.err(16066): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-05 20:47:19.486: W/System.err(16066): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-05 20:47:19.486: W/System.err(16066): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-05 20:47:19.486: W/System.err(16066): at java.net.Socket.connect(Socket.java:872)
03-05 20:47:19.486: W/System.err(16066): at libcore.net.http.HttpConnection.(HttpConnection.java:77)
I think the exception log is as described as above. So what's wrong here?
I have tried AsyncTask as some of you suggested.
The code is as belowed:
private class HttpGetTask extends AsyncTask<Void , Void, String> {
private String URL = "http://192.168.1.100:9080/" + "?" +"content1="+resultString;
//buf.append("content1="+URLEncoder.encode(resultString,"UTF-8"));
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
//Log.e("check", "succeed");
#Override
protected String doInBackground(Void... param) {
HttpGet request = new HttpGet(URL);
//Log.e("check1","succeed");
Log.e("url",URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
Log.e("check3","succeed");
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
Log.e("check4","succeed");
} catch (IOException exception) {
exception.printStackTrace();
Log.e("check5","succeed");
}
Log.e("check6","succeed");//to this point
return null;
}
#Override
protected void onPostExecute(String result) {
if (null != mClient)
mClient.close();
//Log.e("check6","succeed");
mTextView.setText(result);
}
}
03-06 14:57:07.117: W/System.err(12451): org.apache.http.conn.ConnectTimeoutException: Connect to /192.168.1.100:9080 timed out
03-06 14:57:07.137: W/System.err(12451): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
03-06 14:57:07.137: W/System.err(12451): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
the Log shows that there is an IOException in my codes and the value of mClient will eventually be null.I have looked online for the same situation and it seems this occurs when data takes too much time to respond that is requested. And many of the answers suggested I should reset Timeout and allow more time for the request to be sent. But I don't really understand where to put the reset codes in my situation. Can anyone help with this? Thanks.

NetworkOnMainThreadException is thrown when you try to perform network operations on the main/UI thread. This is not allowed in Android. Instead, you need to perform network operations in a background thread. You can do this using an AsyncTask.

You can put this on onCreate(), but the best option is to use AsyncTask.
StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);

Related

Async task crashes the aplication on android when internet is unavailable

In my android app I've used a async task to handle my internet request. I achieved that by using the okhttp library, which makes it easy to make internet requests. I have a lot of the code surrounded my try/catch statements, but they somehow do not trigger when there is an unhandled exception so the app crashes. That only happens when the internet is disconnected or is slow in areas.
I've looked for similar posts, but found out that people who had the same problems didn't try/catch, so the exceptions weren't handled
I've also tried to make a checker for the internet accessibility, but that didn't work out too well, because i would much rather do it with clean try-catching.
private class prenesi extends AsyncTask<String, Void, String>
{
String odgovor = null;
protected String doInBackground(String... params)
{
OkHttpClient client = new OkHttpClient();
RequestBody vsebina = new FormEncodingBuilder()
.add("kraj", params[0])
.build();
Request request = new Request.Builder()
.url("http://mypage.com/login.php")
.post(vsebina)
.build();
Response response = null;
try
{
response = client.newCall(request).execute();
}
catch (IOException e)
{
e.printStackTrace();
}
if (!response.isSuccessful())
{
odgovor = "Napaka.";
}
else
try
{
odgovor = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
return odgovor;
}
}
The devconsole says the problem is in the doInBackground() and i guess it caused because the null pointer exception, though I'm not entirely sure what that means:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
Could somebody point me towards the flaw please. I'm stuck with this.
All the help will be very appreciated, hope to solve this problem soon.
Thanks for contributing.
It seems that you forgot to initialize your String value. Run it by first setting String odgovor=""; instead of String odgovor= null;
Try modifying the code to this
String odgovor="";
try{
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
odgovor = "Napaka.";
} else{
odgovor = response.body().string();
}} catch (IOException e) {
e.printStackTrace();
}
Seems the problem in the end was with the isSuccessul method, which was a bit cheesy, idk why, but instead of it i used if(response == null).

Android API error / httpget NetworkOnMainThreadException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
This is my error message:
08-17 07:58:14.286 32620-32620/xxx.dk.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: xxx.dk.xxx, PID: 32620
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239)
at java.net.InetAddress.lookupHostByName(InetAddress.java:388)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at xxx.dk.xxx.DAL.JsonConnection.checkSecret(JsonConnection.java:42)
at xxx.dk.xxx.BLL.CheckCarrierData.checkSecret(CheckCarrierData.java:14)
at xxx.dk.xxx.GUI.Login.onClick(Login.java:49)
at android.view.View.performClick(View.java:4480)
at android.view.View$PerformClick.run(View.java:18686)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Im trying to use a httpGet method, which is working on API10, but it fails when im using it on an unit with 4.4.2 -> i need the support from API10 and up.
The code:
public class JsonConnection
{
private String secretJsonStr = null;
private String nameOfCarrier = "";
public String checkSecret(String secret)
{
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
final String QueryParam = "secret";
try
{
final String httpUrl = "***SOMEURL***?";
Uri builtUri = Uri.parse(httpUrl).buildUpon().
appendQueryParameter(QueryParam, secret.toString()).build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
{
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if (buffer.length() == 0)
{
// Stream was empty. No point in parsing.
return null;
}
secretJsonStr = buffer.toString();
} catch (IOException e)
{
Log.e("Login", "Error", e);
return null;
} finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
if (reader != null)
{
try
{
reader.close();
} catch (final IOException e)
{
Log.e("Login", "Error closing stream", e);
}
}
}
try
{
JSONObject secretJson = new JSONObject(secretJsonStr);
nameOfCarrier = getCarrierInfoFromJson(secretJson);
}
catch (JSONException e)
{
e.printStackTrace();
}
return nameOfCarrier;
}
private String getCarrierInfoFromJson(JSONObject secretJson)
throws JSONException
{
final String CARRIER_NAME = "Name";
String nameOfCarrier2 = secretJson.getString(CARRIER_NAME);
return nameOfCarrier2;
}
}
Due to some protection, i cannot show you the URL, but everything is working like a charm when running in API 10 2.3.6 units..
I though there where complete backwards compatibility on all android devices.
Hope you have the knowledge to help me on, I for sure cannot see how. :-(
Kindest regards
Rasmus
The problem is that the http requests are executed on the main thread (NetworkOnMainThreadException), so you need to move the calls into a Thread. More info here.
update: actually, possible duplicate of this.
As error say you can't execute an HTTP connection on the MainThread that would froze the screen. which is not appropriate.
You can get that permission as the following:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But, this is not a good practice. you must run the http connection on a background thread and display a loading msg to the user.
new Thread(new Runnable() {
#Override
public void run() {
// code goes here ...
}
}).start();
As other answers are suggesting, you are getting this error because you are running network operation on main thread. I would suggest to use AsyncTask.
This link shows you structure of AsyncTask.
To call the AsyncTask, use
//getData() is name of class
new getData().execute();
More reference on Android Developer site.

java.io.IOException: Received authentication challenge is null in ICS 4.0.3

I'm trying to logoff from the server. But it returns "0" response code with this exception. I'm using GET verb to do this.
LogCat
10-17 14:54:13.261: W/System.err(868): java.io.IOException: Received authentication challenge is null
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:397)
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:345)
10-17 14:54:13.304: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:276)
10-17 14:54:13.324: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
10-17 14:54:13.324: W/System.err(868): at com.remote.synchronizer.haris.CustomHttpClient.executeGet(CustomHttpClient.java:131)
10-17 14:54:13.354: W/System.err(868): at com.remote.synchronizer.haris.OptionsActivity$1$3$1.run(OptionsActivity.java:87)
10-17 14:54:13.364: W/System.err(868): at android.os.Handler.handleCallback(Handler.java:605)
10-17 14:54:13.384: W/System.err(868): at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 14:54:13.384: W/System.err(868): at android.os.Looper.loop(Looper.java:137)
10-17 14:54:13.404: W/System.err(868): at android.app.ActivityThread.main(ActivityThread.java:4424)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invokeNative(Native Method)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invoke(Method.java:511)
10-17 14:54:13.454: W/System.err(868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-17 14:54:13.474: W/System.err(868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 14:54:13.474: W/System.err(868): at dalvik.system.NativeStart.main(Native Method)
10-17 14:54:13.484: E/HTTP Response(868): java.io.IOException: Received authentication challenge is null
CustomHttpClient.java
public class CustomHttpClient {
static HttpClient client = new DefaultHttpClient();
static HttpURLConnection connection = null;
public static int executePost(String url, String postParameters)
{
int response=0;
OutputStream output = null;
try
{
connection = (HttpURLConnection)new URL(url).openConnection();
System.setProperty("http.keepAlive", "false");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.connect();
output = connection.getOutputStream();
output.write(postParameters.getBytes("UTF-8"));
response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}
finally {
if(connection != null) {
// connection.disconnect();
if (output != null)
try { output.close(); }
catch (IOException logOrIgnore) {}
}
}
return response;
}
public static int executeGet(String url)
{
int response=0;
//HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) new URL(url).openConnection();
System.setProperty("http.keepAlive", "false");
//connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}
finally {
if(connection != null) {
// connection.disconnect();
}
}
return response;
}
}
Before this I'm using DefaultHTTPClient in Gingerbird 2.3 its working perfectly but in ICS DefaultHTTPClient is not working so I need to use HttpURLConnection. POST verb is working fine.
You can get the response code after an exception if you call .getResponseCode() a second time on the connection object. This is because the first time you call .getResponseCode() an internal state is set that enables .getResponseCode() to return without throwing an exception.
Example:
HttpURLConnection connection = ...;
try {
// Will throw IOException if server responds with 401.
connection.getResponseCode();
} catch (IOException e) {
// Will return 401, because now connection has the correct internal state.
int responsecode = connection.getResponseCode();
}
I have also answered this question here: https://stackoverflow.com/a/15972969/816017
HttpURLConnection.getResponseCode() throws java.io.IOException: Received authentication challenge is null when it encounters malformed HTTP 401 header. Do you receive WWW-Authenticate and Content-Length headers from server in addition to HTTP/1.1 401 Unauthorized header? See IOException: "Received authentication challenge is null" (Apache Harmony/Android)
If you can't make changes to server, then you can catch that exception (thanks https://stackoverflow.com/a/10904318/262462)
try {
response=connection.getResponseCode();
}
catch (java.io.IOException e) {
if (e.getMessage().contains("authentication challenge")) {
response = HttpsURLConnection.HTTP_UNAUTHORIZED;
} else { throw e; }
}
This error happens beause the server sends a 401 (Unauthorized) but does not give a "WWW-Authenticate" which is a hint for the client what to do next. The "WWW-Authenticate" Header tells the client which kind of authentication is needed (either Basic or Digest). This is usually not very useful in headless http clients, but thats how the standard is defined. The error occurs because the lib tries to parse the "WWW-Authenticate" header but can't.
Possible solutions if you can change the server:
Add a fake "WWW-Authenticate" header like: WWW-Authenticate: Basic realm="fake". This is a mere workaround not a solution, but it should work and the http client is satisfied.
Use HTTP status code 403 instead of 401. It's semantic is not the same and usually when working with login 401 is a correct response (see here for detailed discussion) but its close enough.
Possible solutions if you can't change the server:
As #ErikZ wrote in his post you could use a try&catch
HttpURLConnection connection = ...;
try {
// Will throw IOException if server responds with 401.
connection.getResponseCode();
} catch (IOException e) {
// Will return 401, because now connection has the correct internal state.
int responsecode = connection.getResponseCode();
}
I also posted this here: java.io.IOException : No authentication challenges found

HttpHostConnectException: Connection refused Android

I am trying to connect via HttpPost and send a username and password to a website and then receive a string from that website. I have tried various methods that have worked for me in the past but now when I send the username and password identifiers the app times out for as long as 4 minutes and then spits out the following exception:
07-16 16:32:32.897: W/System.err(632): Unable to connect to the server
07-16 16:32:32.907: W/System.err(632): org.apache.http.conn.HttpHostConnectException: Connection to http://devdashboard.company refused
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-16 16:32:32.927: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.HttpHelperAndroid.sendToHttp(HttpHelperAndroid.java:66)
07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.DashboardAppActivity.goToDashboard(DashboardAppActivity.java:62)
07-16 16:32:32.927: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.937: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.937: W/System.err(632): at android.view.View$1.onClick(View.java:3039)
07-16 16:32:32.947: W/System.err(632): at android.view.View.performClick(View.java:3511)
07-16 16:32:32.947: W/System.err(632): at android.view.View$PerformClick.run(View.java:14105)
07-16 16:32:32.947: W/System.err(632): at android.os.Handler.handleCallback(Handler.java:605)
07-16 16:32:32.957: W/System.err(632): at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 16:32:32.957: W/System.err(632): at android.os.Looper.loop(Looper.java:137)
07-16 16:32:32.967: W/System.err(632): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.977: W/System.err(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-16 16:32:32.987: W/System.err(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-16 16:32:32.987: W/System.err(632): at dalvik.system.NativeStart.main(Native Method)
07-16 16:32:32.987: W/System.err(632): Caused by: java.net.ConnectException: failed to connect to /50.19.240.232 (port 80): connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:32.997: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:114)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-16 16:32:33.007: W/System.err(632): at java.net.Socket.connect(Socket.java:842)
07-16 16:32:33.007: W/System.err(632): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-16 16:32:33.017: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-16 16:32:33.017: W/System.err(632): ... 22 more
07-16 16:32:33.027: W/System.err(632): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:33.047: W/System.err(632): at libcore.io.Posix.connect(Native Method)
07-16 16:32:33.047: W/System.err(632): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
07-16 16:32:33.047: W/System.err(632): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-16 16:32:33.057: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:112)
07-1
6 16:32:33.057: W/System.err(632): ... 27 more
Internet permission IS enabled in my XML manifest file
My current implementation goes like this:
String LOGIN = "email#gmail.com";
String PASSWORD ="password1";
//JSONObject to send the username and pw
JSONObject json = new JSONObject();
//put the path in the JSONArray object
JSONArray vect = new JSONArray();
vect.put("company Android Library");
vect.put("Rocket Ship");
int duration = 50;
try {
json.put("email", LOGIN);
json.put("password", PASSWORD);
json.put("json", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "ABOUT TO SEND:" + json.toString());
JSONObject inJson = HttpHelperAndroid.sendToHttp(json, "http://devdashboard.company/login");
if(inJson != null)
{
Log.d(TAG, "RECIEVED the JSON:" + inJson.toString());
}
else
Log.d(TAG, "THE RESPONSE WAS NULL");
}
And the HttpHelperAndroid class looks like so:
public class HttpHelperAndroid
{
private static final String TAG = "HttpHelperAndroid";//TAG for the LogCat(debugging)
private static boolean responseSuccessful = true;
/**
* sends the JSONObject parameter to the desired URL parameter and gets the response
*
* #param url the URL to which the JSONObject should be sent
* #param jsonObjOut the JSONObject that is to be sent
* #return the response from the server as a JSONObject
*/
public static JSONObject sendToHttp(JSONObject jsonObjOut, String url) {
responseSuccessful = true;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(url);
//convert the JSONObject to a string
StringEntity se;
//set our StringEntity to the JSONObject as a string
se = new StringEntity(jsonObjOut.toString());
// Set HTTP params
httpRequest.setEntity(se);
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression
//get the current time
long oldTime = System.currentTimeMillis();
HttpResponse response = null;
try
{
//execute the http request and get the response
response = (HttpResponse) httpClient.execute(httpRequest);
}
catch(HttpHostConnectException e)
{
System.err.println("Unable to connect to the server");
e.printStackTrace();
responseSuccessful = false;
}
//only continue executing if we got a response from the server
if(responseSuccessful)
{
//print how long the response took to the LogCat if it's on
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-oldTime) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream in = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}
// convert content stream to a String
String resultString= streamToString(in);
//close the stream
in.close();
// convert the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
//take a peak at the JSONObject we got back if the LogCat is on
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
//return the JSONObject we got back from the server
return jsonObjRecv;
}
}
}
//catch any exception that was thrown
catch (Exception e)
{
//Print the exception
e.printStackTrace();
}
return null;
}
private static String streamToString(InputStream is)
{
//create a new BufferedReader for the input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//create a new StringBuilder to append the lines
StringBuilder sb = new StringBuilder();
//initialize an empty string
String line = null;
try
{
//iterate as long as there is still lines to be read
while ((line = reader.readLine()) != null)
{
//append the line and a newline character to our StringBuilder
sb.append(line + "\n");
}
}
//catch an IOException and print it
catch (IOException e) {
e.printStackTrace();
}
//close the stream when we're done
finally
{
try
{
is.close();
}
//catch and print an exception if it's thrown
catch (IOException e)
{
e.printStackTrace();
}
}
//return the stream converted to a string
return sb.toString();
}
}
And here is my XML just for kicks:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="company.android.dashboard.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/company_android_ico"
android:label="#string/app_name" >
<activity
android:name=".DashboardAppActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have used the HttpHelper class in past projects and it has worked for me, in addition I tried to implement this using nameValuePairs:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "email#gmail.com"));
nameValuePairs.add(new BasicNameValuePair("password", "password1"));
nameValuePairs.add(new BasicNameValuePair("json", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
And this yielded the same result.
Could this somehow be a certificate thing? or perhaps something to do with a corrupt XML file( I tried remaking the project and the xml file) Android HTTP Connection refused
Or maybe some sort of Android hosts file issue?
I'm open to any suggestions!
I have examined this from a lot of angles and I'm happy to provide any other information that would be helpful! I really appreciate your time!
NOTE: The url is a dummy url, and not the actual one I am connecting to, for security reasons. I am able to curl the actual website from the command line with the parameters and it works and I am also able to login normally from the web browser.
EDIT I have identified the problem! But not the solution unfortunately. So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server. So to fix this I somehow need to edit the hosts file on my Android device/in the emulator...does anyone know how this can be done legitimately?
I have identified the problem! So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server.
So there are two possible solutions to this issue:
1) Editing the hosts file on the Android device (requires rooting your phone): How to change the hosts file on android
2) Getting the server registered on the global DNS server.
(also hard to do if you're not responsible for the url)
Anyways I hope this helps someone else too!
Please follow these solution may be among these one solve your issue.
1> check your manifest file internet permission there or not.
2> check your url with browser by rest client and pass the appropriate request.
3> open the url in mobile like:- http://your ip address/port that's it just for checking do you have a permission or not to open this url in mobile.
There are a few possibilities
1) the url is incorrect "http://devdashboard.company/login" is not right. At least check in browser.
ping the host as well.
2) This should be an https connection instead.
3) there is some certification required.
4) You are missing a port number. or domain has not been setup correctly.
perhaps port 80 the default is incorrect?
5) the call should not be a post.
In general you are either responsible for the server or you are not. It appears that it is some elses responsibility, and you should ask them what the correct url and parameters are. So its probably no ones fault, but you need to ask them about the connection to verify.
The other thing you can do is to try and see what the url looks like in an application that is succesfully connectiing. take a look that this.
The problem is in wifi sleeping.
Please use
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
wifiLock.acquire();
and permission:
uses-permission android:name="android.permission.WAKE_LOCK";
This post is old, but it is the first result when googling this error. I encountered the same exception, and everything was completely correct in my code. I commented out the line containing the INTERNET permission in my AndroidManifest.xml, ran the app, clicked/tapped my button to send the HTTP request and get the exception, closed the app, went back to the manifest, uncommented the permission line, ran the app again, and the exception was resolved!
This kind of bugs in 2015 (and in "advanced" tools like the latest compile tools for Android API 21, and Intellij IDEA 14) drives me mad! You are approaching your deadline, and this sort of bugs completely disrupts your work!

Twitter + OAuth Integration

Anybody can please help in Android + Twitter Integration using OAuth.
I already worked on http://github.com/brione/Brion-Learns-OAuth and getting the error listed below, when I am posting status update...
WARN/System.err(190): org.apache.http.client.HttpResponseException: Unauthorized
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:343)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:1)
WARN/System.err(190): at android.os.AsyncTask$2.call(AsyncTask.java:185)
WARN/System.err(190): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
WARN/System.err(190): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
WARN/System.err(190): at java.lang.Thread.run(Thread.java:1060)
I succeed with OAuth Authentication and getting user_secret and user_token and stored in preferences...
So the issue is with http posting using OAuth header...
and My Http Post Method is as :
private class PostTask extends AsyncTask<String, Void, JSONObject> {
ProgressDialog postDialog;
#Override
protected void onPreExecute() {
postDialog = ProgressDialog.show(BLOA.this,
getText(R.string.tweet_progress_title),
getText(R.string.tweet_progress_text), true, // indeterminate
// duration
false); // not cancel-able
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jso = null;
try {
HttpPost post = new HttpPost(
"http://twitter.com/statuses/update.json");
LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
out.add(new BasicNameValuePair("status", params[0]));
post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
post.setParams(getParams());
// sign the request to authenticate
mConsumer.sign(post);
String response = mClient.execute(post,
new BasicResponseHandler());
jso = new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
return jso;
}
// This is in the UI thread, so we can mess with the UI
protected void onPostExecute(JSONObject jso) {
postDialog.dismiss();
if (jso != null) { // authorization succeeded, the json object
// contains the user information
mEditor.setText("");
mLast.setText(getCurrentTweet(jso));
} else {
mLast.setText(getText(R.string.tweet_error));
}
}
}
Although you are received the user_secret and user_token successfully in onResume(), are you sure your original objects are still the same? I had this problem in my Android app. I would create the objects, but when onResume() was called it was a totally new instance of the Activity because it was free'd from memory when the browser launched. So when I tried to set the returned secret/token pair it wouldn't work. This is more likely to happen on a device with limited memory. Some people choose to persist the necessary info between calls and others decide to not launch the default browser intent, but rather host an embedded webview so their original signpost-oauth objects don't go out of scope.
OAuth instance state in Android
Not sure if this is the issue, but maybe worth a look.
You need to add the oauth information to the headers of the http request using post.addHeader(). To know which things to add to the headers, take a look here: http://dev.twitter.com/pages/auth
Please describe what Client/Consumer/Provider you are using, they must be DefaultHttpClient/CommonsHttpOAuthConsumer/CommonsHttpOAuthProvider to work properly for sure.
Ensure you call consumer.setTokenWithSecret(oToken, oTokenSecret); before calling this code.
Also, is post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); exists in your post params?
What's the reason for using empty BasicResponseHandler, it handles nothing and it can be omitted in execute call, I suppose.
And, may be a dumb question, may be you are overwriting params when calling setParams(...) after setEntity(...)
I have 2 tutorials for 2 different Java libs. First one (dated) is here, and 2nd one here with Scribe. It's for LinkedIn but it would be very easy to switch to Twitter. I would go with #2

Categories

Resources