Httpclient redirects android - android

The problem is as following :
I use httpclient to post login data to server.
While using firefox on my desktop with live headers the server redirects me to url2 witk 302, then to url3 with 302 and then I get 200 ok. In android I got the same login page and 200 OK.
Then I disabled automatic redirect handling got the response and saw 302 redirect, BUT
"String location = response.getHeaders("Location")[0].toString();" gave me the same login page url and not the one from firefox.
I have no idea why is that.
Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri[0]);
HttpResponse response;
String responseString = null;
HttpParams params = httpclient.getParams();
HttpClientParams.setRedirecting(params, false);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding namvalue pairs here - adding correct i'm sure
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
if (statusLine.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
{
String location = response.getHeaders("Location")[0].toString();
}
response.getEntity().getContent().close();
}
Firefox headers:
What i get is : location= /login/

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.

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

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.

JSON merge two responses in android

I am using JSON to get response from my server.
This is code:
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response;
HttpResponse response2;
try {
HttpGet request = new HttpGet(GlobalConfig.getMagazineUrl());
HttpGet request2 = new HttpGet(GlobalConfig.getMagazinePagesUrl(1));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
request2.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
response = httpclient.execute(request);
StatusLine statusLine = response.getStatusLine();
response2 = httpclient2.execute(request2);
StatusLine statusLine2 = response2.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK && statusLine2.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
response2.getEntity().writeTo(out2);
out.close();
out2.close();
return parser(out.toString(), out2.toString());
As you can see in parser(out.toString(), out2.toString()) I return both responses as String. I would like to know how I can merge this two JSON responses in one. I don't want to merge two strings, I need merge two JSON respons in one big response. This is possible? If yes how I can do that?
Perhaps thats what you want:
...
JSONObject json = new JSONObject();
json.put("response1", new JSONObject(out.toString()));
json.put("response2", new JSONObject(out2.toString()));
Now return either json.toString() or json depending on the return type.

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

Categories

Resources