Http Authentication via Android - 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.

Related

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.

Httpclient redirects 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/

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.

Android Getting JSON return error from POST Http execution

I'm currently trying to send data via POST to a server, and the server is handling the data and appends it to a JSON file. I'm currently getting a 422 error and I've been receiving it for a while now. My question is: How do I receive that JSON error itself in Java so that I can see what the error is. All I'm seeing is a HttpResponseException and it doesn't give me anything else. Thanks for the time and help in advance.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mPath);
// Add your data
try
{
List nameValuePairs = new ArrayList(4);
httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(bundleId).append(":").append(apiKey).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
nameValuePairs.add(new BasicNameValuePair("state", "CA"));
nameValuePairs.add(new BasicNameValuePair("city", "AndDev is Cool!"));
nameValuePairs.add(new BasicNameValuePair("body", "dsads is assrawstjljalsdfljasldflkasjdfjasldjflasjdflkjaslfggddsfgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfdsgfddjflaskjdfkasjdlfkjasldfkjalskdjfajasldfkasdlfjasljdflajsdfjasdjflaskjdflaksjdfljasldfkjasljdflajsasdlfkjasldfkjlas!"));
nameValuePairs.add(new BasicNameValuePair("title", "dsaghhhe fd!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost);
//int status = response.getStatusLine().getStatusCode();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Log.v(TAG, "response: " + responseBody);
//JSONObject response = new JSONObject(responseBody);
int f = 0;
}
catch(HttpResponseException e)
{
Log.e(TAG, e.getLocalizedMessage());
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
you may send your parameters more conveniently by using predefined Json class as below:
String jsonParam = null;
try{
JSONObject param = new JSONObject();
param.put("state", "CA");
param.put("city", "AndDev is Cool!");
//and so on with other parameters
jsonParam = param.toString();
}
catch (Exception e) {
// TODO: handle exception
}
and set the post entity as:
if(jsonParam != null)
httppost.setEntity(new StringEntity(jsonParam, HTTP.UTF_8));
422 error says: Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors
You got a problem with UrlEncodedFormEntity

Android - image upload sending no content

I've been looking into this for the last day or two and can not seem to find a solution to my issue. I am trying to post an image to a server using httppost.
I have tried two ways of doing this and both complete the post but with no content i.e. the content length is 0.
The first is as follows:
String url = "MYURL";
HttpClient httpClient = new DefaultHttpClient();
try {
httpClient.getParams().setParameter("http.socket.timeout", new Integer(90000)); // 90 second
HttpPost post = new HttpPost(url);
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/DCIM/100MSDCF/DSC00004.jpg");
FileEntity entity;
entity = new FileEntity(file,"binary/octet-stream");
entity.setChunked(true);
post.setEntity(entity);
post.addHeader("Header", "UniqueName");
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Log.e("Here","--------Error--------Response Status line code:"+response.getStatusLine());
}else {
// Here every thing is fine.
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
Log.e("Here","---------Error No Response!!-----");
}
} catch (Exception ex) {
Log.e("Here","---------Error-----"+ex.getMessage());
ex.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
and the second is:
String url = "MYURL";
//File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(Environment.getExternalStorageDirectory(),"/DCIM/100MSDCF/DSC00004.jpg");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.d("finishing", "The try catch function");
} catch (Exception e) {
// show error
}*/
As you can see I have hardcoded a path to a specific image, this is to be dynamic when I get it up and running.
Can anyone see what i'm doing wrong? Am I leaving out something? I know I use setChunked and setContenttype - is there a setContent option?
Any help would be grately appreciated.
Thanks,
jr83.
You can use upload your image by sending multipart messages; you might find this discussion useful.

Categories

Resources