Android:Trying to make an httpPost Request but keep getting connection timeout - android

I am really in pain right now please help me solve this issue.
I've previously also tried to make the http request to my localhost and it all works fine but right now it is not working and I don't know why.
I am trying to make the request from the following code.
HttpClient httpclient = new DefaultHttpClient();
String result="";
try
{
HttpPost httppost = new HttpPost("http://[ip]/php/untitled.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",this.userEmail));
nameValuePairs.add(new BasicNameValuePair("pwd",this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity!=null)
{
InputStream inputStream=entity.getContent();
result= convertStreamToString(inputStream);
}
}
catch (ClientProtocolException e)
{
Log.e("errorhai",e.getMessage());
}
catch (IOException e)
{
Log.e("errorhai",e.getMessage());
}
return result;
I've also added the internet permission but still it keeps saying
Connect to [ip] timed out.
When I enter the url in my browser it works fine but it is not working here.Please tell me what can be the causes of this problem ?

you can set the time out parameter to handle such type of exception :
HttpParams httpParameters = new BasicHttpParams();
/* Set the timeout in milliseconds until a connection is established.
The default value is zero, that means the timeout is not used.*/
int timeoutConnection = 60*1000*1;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
/* Set the default socket timeout (SO_TIMEOUT)
in milliseconds which is the timeout for waiting for data. */
int timeoutSocket = 60*1000*1;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
//HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
/** Finally, we send our request using HTTP. This is the synchronous
long operation that we need to run on this thread. */
httpResponse = client.execute(request);
/*int responseCode = httpResponse.getStatusLine().getStatusCode();
String message = httpResponse.getStatusLine().getReasonPhrase();*/
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String res = convertStreamToString(instream);
MLog.v("HTTP RESPONSE : ", "Res :-"+res);
if(!res.trim().equalsIgnoreCase("[]")){
response.setResult(res);
response.setSuccess(true);
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.RECORD_NOT_FOUND);
}
/** Closing the input stream will trigger connection release */
instream.close();
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
}
catch (Exception e) {
//client.getConnectionManager().shutdown();
e.printStackTrace();
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
//you can again try to send request , if your response is not sucess.
//retryHttpRequestIfNotSucess();

your problem might be related to the login. Is your script expecting a preemptive authetification? Do you have a error page for a failed login?
For requesting a page with preemptive http basic authentication i'm using the following code that is working. Have a try, if its working for you too.
DefaultHttpClient httpclient = null;
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
HttpEntity entity = null;
// Set connection parameter
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
httpclient = new DefaultHttpClient(params);
// Create a post statement
HttpPost httppost = new HttpPost(Constants.urlLogin);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
httppost.getParams().setParameter("http.protocol.single-cookie-header", true);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("login_name", this.username));
nvps.add(new BasicNameValuePair("login_passwd", this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httppost);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String loadedContent = null;
if (entity != null)
{
loadedContent = EntityUtils.toString(entity, HTTP.UTF_8);
// loadedContent =
// Helper.convertStreamToString(entity.getContent());
entity.consumeContent();
}
if (statusCode != (HttpStatus.SC_OK))
{
throw new ServerCommunicationErrorException();
} else if (!loadedContent.contains("Logout"))
{
// Login failed
throw new LoginFailedException();
}
As you can see, i get a "not logged in" page as result, if the login fails to determine the login process. Further more i set some parameters, that might be also interesting for you. You can look here for more information on parameters.

Related

Http Authentication via Android

I currently try to make an authentication on Android the same way I'm doing it with Postman here.
I followed some examples everywhere on the Internet and I came up with this code :
protected String doInBackground(Void... voids) {
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("_username", mylogin));
nameValuePairs.add(new BasicNameValuePair("_password", mypassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
StatusLine status = response.getStatusLine();
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Status Error CODE : " + status.getStatusCode());
}
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int readCount;
while ((readCount = in.read(buff)) != -1)
{
out.write(buff, 0, readCount);
}
return new String (out.toByteArray());
}catch (Exception e){
e.printStackTrace();
}
return null;
}
I keep getting an Error 401 and I don't understand why. Is there anything that I'm not seeing ?
By the way I also try to use its method but didn't get better.
Thanks for helping me !
Find the solution, the problem wasn't from Android but from the server under Symphony. Symphony needed to create a session before accepting requests.

Android - Cookies in HttpContext is not retrieving more than once for each URL

I'm trying to retrieve JSon information for a server that is protected and is redirected to the login page everytime that is trying to get a protected resource. So I should use cookies to implement the access to the information.
Unfortunately POST for each URL(in total 3)that I have, is just working once.
To log in the app is made using the function below:
// Making HTTP request
try {
httpClient = getNewHttpClient();
String redirectedUrl = getUrl(url);
// defaultHttpClient
HttpPost httpPost = new HttpPost(redirectedUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", login));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpContext = new BasicHttpContext();
CookieStore mCookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
if ((html != null) && html.contains("error loginError")) {
} else
return html;
} catch (IOException e) {
}
And after the log in I'm trying to get the information in the same way, but it's just working once per URL. I don't know why, below is how I'm trying to get the information after login.
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, httpContext);
HttpEntity entity = response.getEntity();
String html = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
html = streamToString(instream);
} finally {
instream.close();
}
}
When I'm trying to get the information second time the IOException is throwed, the httpClient and httpContext are both global and static.
I got a solution, I don't think that is a good solution, but it is working at all.
To make it stops to get the IOException, I just made a call to the login function before all post, which means that for all POSTs I have to set a new HTTPContext logged and valid.
If somebody has a better solution I would be pleasure to hear it from you.
PS.: Actually the problem was about the session duration on server side, now it's working properly, anyway I'll let the topic here because could be useful to somebody that is implementing this kind of solution.

How to cache the response of Http Client in Android App?

In my android application I am trying to cache the response of Http Client
The console always shows the "The response came from an upstream server" message when I call the url.
My code for Http Client is as follows:
try
{
CacheConfig cacheConfig = new CacheConfig();
cacheConfig.setMaxCacheEntries(1000);
cacheConfig.setMaxObjectSizeBytes(8192);
DefaultHttpClient realClient = new DefaultHttpClient();
realClient.addResponseInterceptor(MakeCacheable.INSTANCE, 0); // This goes first
CachingHttpClient httpClient = new CachingHttpClient(realClient, cacheConfig);
HttpContext localContext = new BasicHttpContext();
String requestUrl= SERVER_IP+ ANDROID_REQUEST_URL+METHOD_GET_ALLDEALS;
HttpPost httppost = new HttpPost(requestUrl);
ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
BasicNameValuePair latitudeValue=new BasicNameValuePair("lat",String.valueOf(28.460190279993547));
BasicNameValuePair longitudeValue=new BasicNameValuePair("lng",String.valueOf(77.0645221799944));
BasicNameValuePair radiusValue=new BasicNameValuePair("radius",String.valueOf(10));
BasicNameValuePair catIdValue=new BasicNameValuePair("cat",String.valueOf(1));
BasicNameValuePair subCategoryIdValue=new BasicNameValuePair("subcat",String.valueOf(0));
BasicNameValuePair offsetValue=new BasicNameValuePair("offset",String.valueOf(0));
BasicNameValuePair deviceIdvalue=new BasicNameValuePair("deviceId","12366A4C-9CD0-47F4-9ACC-D1CD7DD997FC");
BasicNameValuePair sessionIdValue=new BasicNameValuePair("sessionId","10873");
nameValuePairs.add(latitudeValue);
nameValuePairs.add(longitudeValue);
nameValuePairs.add(radiusValue);
nameValuePairs.add(catIdValue);
nameValuePairs.add(subCategoryIdValue);
nameValuePairs.add(offsetValue);
nameValuePairs.add(deviceIdvalue);
nameValuePairs.add(sessionIdValue);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String paramString = URLEncodedUtils.format(nameValuePairs,"utf-8");
String url = requestUrl+"?"+paramString;
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpClient.execute(httpget,localContext);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = readIncomingData(instream);
instream.close();
Log.i("MainActivity", result);
}
CacheResponseStatus responseStatus = (CacheResponseStatus) localContext.getAttribute(
CachingHttpClient.CACHE_RESPONSE_STATUS);
switch (responseStatus) {
case CACHE_HIT:
Log.e("","A response was generated from the cache with no requests " +
"sent upstream");
break;
case CACHE_MODULE_RESPONSE:
Log.e("","The response was generated directly by the caching module");
break;
case CACHE_MISS:
Log.e("","The response came from an upstream server");
break;
case VALIDATED:
Log.e("","The response was generated from the cache after validating " +
"the entry with the origin server");
break;
}
}catch (Exception e) {
Log.i("MainActivity",e.getMessage());
}
I use the following block of code and call it in onCreate()
private void enableHttpResponseCache() {
try {
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
File httpCacheDir = new File(getCacheDir(), "http");
Class.forName("android.net.http.HttpResponseCache")
.getMethod("install", File.class, long.class)
.invoke(null, httpCacheDir, httpCacheSize);
Log.i(LOGTAG,"cache");
} catch (Exception httpResponseCacheNotAvailable) {
Log.i(LOGTAG,"nocache");
}
}
Bear in mind this will only enable caching on 4.0+ devices. Any lower than that and you will see "nocache" in the logs.

Sending Video using HTTP Post Multipart entity

What I want I want to send a video from my SDcard to a server. I also want to send some parameters/value with it.
I have tried I have tried the following code:
public String SendToServer(String aUrl,File aFile)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(aUrl);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(aFile));
entity.addPart("video[title]", new StringBody("testVideo"));
entity.addPart("video[type]", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
What is the problem When I run this code, I get stuck at this line
HttpResponse response = httpClient.execute(httpPost, localContext);
I get no exception, no response nothing at all. Can anyone please guide me, what is the problem in here?
The above code in my question was perfect, but I had the network problem. My device was connected to a hotspot(Connectify Software). When I connected to the original network, this code worked perfect.
I recommend you people to never trust a hotspot for this kind of functionality.
try using this way if want to send as content or esle I will upload the project by tonight
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(filePath), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);

Android httpclient request and processing with entity

I do requests to my servlet
try {
Log.d(Constants.DEBUG_TAG_MAPS, "try");
HttpEntity entity = new StringEntity(json);
post.setEntity(entity);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 150000);
httpclient = new DefaultHttpClient(httpParameters);
BasicHttpResponse response = (BasicHttpResponse ) httpclient.execute(post);
Log.d(Constants.DEBUG_TAG_MAPS, "http status code : "+response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() == 200){
Log.d(Constants.DEBUG_TAG_MAPS, "response 200");
HttpEntity responseEntity = response.getEntity();
if (responseEntity!= null) {
Gson g = new Gson();
InputStream is = responseEntity.getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
try{
responseEntity.getContent();
String x = EntityUtils.toString(responseEntity);
}catch (Exception e) {
// TODO: handle exception
}
responseJSONObject = g.fromJson(reader, JSONResponseObject.class);
Log.d(Constants.DEBUG_TAG_MAPS_console, responseJSONObject.toString());
reader.close();
System.gc();
}
}
} catch (Exception e) {
e.printStackTrace();
}
/code>
and on line :
InputStream is = responseEntity.getContent();
app is crashing ...response code is 200 ...
I have looked on my tomcat logs and everything is ok. JSONResponseObject is filled with values and sended.
What could be the problem? How can I get stacktrace to logcat?
One maybe related problem:
I have well know "Couldn't et connection factory client" in logcat
Any of thing could causing that issue is not my case
api key is correct, path to correct debug.keystore
all permissions in manifest
uses-library android:name="com.google.android.maps in manifest as well
Map is displayed correctly, refreshing on zooming/moving.
Problem solved after anotate json objects with google.gson.annotations instead of just implementing serializable.

Categories

Resources