Reputation: 163
Hello i got the Problem that my app is so slow with this error:
java.net.ProtocolException: Too many redirects: 21
Now i dont know why it is soo slow, and gets the error, the only thing the website does it opens the php document and start the bash command. :( so it should redirect only 1 time
Thanks :)
I will switch the lights on with a button in the app:
public void switchLightOn(View view) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
CharSequence text = "An";
Toast.makeText(context, text, duration).show();
URL url11 = null;
try {
url11 = new URL("http://192.168.2.104/homepage/steuerung/steckdosen.php?id=1&status=1");
} catch (Exception e) {
e.printStackTrace();
}
new OpenUrlConnection().execute(url11);
}
public void switchLightOff(View view) {
// ausschalten
Context context = getApplicationContext();
CharSequence text = "Aus";
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
URL url10 = null;
try {
url10 = new URL("http://192.168.2.104/homepage/steuerung/steckdosen.php?id=1&status=0");
} catch (Exception e) {
e.printStackTrace();
}
new OpenUrlConnection().execute(url10);
}
private class OpenUrlConnection extends AsyncTask<URL, Void, Integer> {
public Integer doInBackground(URL... urls) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
EDIT:
now i am using:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(String.valueOf(urls[0]));
HttpResponse response = httpclient.execute(httpget);
httpclient.getConnectionManager().shutdown();
but get these errors:
05-06 18:10:36.803 30939-31047/de.carsten.raspicontrol D/dalvikvm﹕ GC_FOR_ALLOC freed 239K, 2% free 17052K/17324K, paused 10ms, total 10ms
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ org.apache.http.client.ClientProtocolException
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:557)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at de.carsten.raspicontrol.RasPiControl$OpenUrlConnection.doInBackground(RasPiControl.java:103)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at de.carsten.raspicontrol.RasPiControl$OpenUrlConnection.doInBackground(RasPiControl.java:97)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ Caused by: org.apache.http.client.CircularRedirectException: Circular redirect to 'http://192.168.2.104/homepage/steuerung/steckdosen.php?id=1&status=0'
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.DefaultRedirectHandler.getLocationURI(DefaultRedirectHandler.java:173)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.handleResponse(DefaultRequestDirector.java:923)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:475)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-06 18:10:38.163 30939-31047/de.carsten.raspicontrol W/System.err﹕ ... 10 more
Upvotes: 4
Views: 6868
Reputation: 503
In case anyone else is running into this issue, I was using okhttp3 Authenticator in my app. In this particular case, I was attempting to call a login endpoint with incorrect credentials (intentionally), in which case my auth token is empty but I was returning response.request.newBuilder().build()
instead of null
. Returning null
fixed the issue for me.
In other words, don't do this:
class TokenAuthenticator : Authenticator {
override fun authenticate(route: Route?, response: Response): Request {
val token = [get token]
if(token.isNotEmpty()) {
return response.request.newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
}
return response.request.newBuilder().build()
}
}
Do this:
class TokenAuthenticator : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
val token = [get token]
if(token.isNotEmpty()) {
return response.request.newBuilder()
.addHeader("Authorization", "Bearer $token")
.build()
}
return null
}
}
Note the return value for the authenticate(route: Route?, response: Response)
method is nullable, which did the trick. I had overridden it as non-nullable leading to some confusion.
Upvotes: 0
Reputation: 39
I was facing same issue. Even I spent quite a lot amount of time to fix this issue. I found out that issue was coming to due following: When you make a call to some JSON services, sometime services might return you data in raw formats or format which may not be typical application/json
. Your .openConnection()
or InputStreamReader
may not be able to read reponse headers and JSON Data. To fix this issue I tried following and it worked for me.
Used HttpClient httpClient = new DefaultHttpClient();
instead of
(HttpURLConnection) obj.openConnection();
Set allow circular redirect:
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
true);
Set following post headers which is important.
httpPost.setHeader("charset","utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language","en-US,en;q=0.8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
Use StringEntity
Read input stream with UTF-8:
httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);
Here is the sample code which worked for me:
HttpClient httpClient = new DefaultHttpClient();
String url =http://....;
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("charset","utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept-Language","en-US,en;q=0.8");
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
//or you can try httpPost.setContentType("application/x-www-form-urlencoded");
StringEntity requestBody = new StringEntity(jsonBody);
requestBody.setContentType("application/json");
httpPost.setEntity(requestBody); HttpResponse httpresponse = httpClient.execute(httpPost);
org.apache.http.StatusLine statusRespons = httpresponse.getStatusLine();
if ( statusRespons.getStatusCode() > 201 ) {
errorText = statusRespons.getStatusCode() + " : " + statusRespons.toString() + " : " +statusRespons.getReasonPhrase() ;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(),HTTP.UTF_8), 8);
String s = ""; while ((s = buffer.readLine()) != null)
jsonString.append(s);
Upvotes: 1
Reputation: 492
Use HttpClient
connection class
org.apache.http.client.HttpClient
instead of HttpURLConnection
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
HttpPost httpPost = new HttpPost("http:\\www.myweb.com");
HttpResponse response = httpclient.execute(httppost);
responseBody = "";
BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String s = "";
while ((s = buffer.readLine()) != null)
responseBody += s;
Upvotes: 2
Reputation: 57306
Your Android code is perfectly fine - it's the server that's not playing ball. First of all, check that you are calling the correct URL and passing the correct parameters. If all of these are fine, then the problem is definitely on the server side.
If you developed the server code yourself, then post it here and we'll try to help. If it's somebody else's code, then you have to get them to fix it, providing the details of the URL and the error.
Upvotes: 4