I'm using JCIFS library found here to use NTLM authentication in my android app.The app worked fine when it just went to a site and parsed an xml, but now that I added the NTLM auth it doesn't seem to be working. Can anyone tell from this snippet of code if where the problem is between the httpclient and the inputstream?
DefaultHttpClient client = new DefaultHttpClient();
client.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
client.getCredentialsProvider().setCredentials(new AuthScope("http://www.musowls.org",80),
new NTCredentials(username, password, null, "musschool"));
HttpGet request = new HttpGet("http://www.musowls.org/assignments/assignmentsbystudentxml.aspx");
HttpResponse resp = client.execute(request);
HttpEntity entity = resp.getEntity();
InputStream inputStream = entity.getContent();
Try below code it may be help you.
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
NTCredentials creds = new NTCredentials("user_name", "password", "", "http://www.musowls.org/");
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 5000);
HttpPost httppost = new HttpPost("http://www.musowls.org/assignments/assignmentsbystudentxml.aspx");
httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
HttpResponse response = httpclient.execute(httppost); // ERROR HAPPENS HERE
responseXML = EntityUtils.toString(response.getEntity());
Log.d("Responce", responseXML);
1) Download JCIFS from here: http://jcifs.samba.org/
2) Follow the instructions here: http://hc.apache.org/httpcomponents-client-ga/ntlm.html
Been stuck on this problem for way too long.
Check out the answer in this thread to use OkHttp3 for NTLM Authenticated calls:
https://stackoverflow.com/a/42114591/3708094
Related
I am working with converting website into android app.
Same code work for http URL & I can Re-use same Session id.
But in https I get session expired error.
HttpPost get3 = new HttpPost(titleURL);
entity = new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"job.order\",\"fields\":[\"job_code\",\"sale_order_id\",\"partner_id\",\"ins_postcode\",\"client_order_ref\",\"cust_po_ref_blanket\",\"engineer_id\",\"appointment\",\"state\"],\"domain\":[[\"state\",\"=\",[\"draft\",\"confirmed\",\"installed\",\"onhold\",\"reject\",\"accepted\"]]],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":1,\"search_default_open_job\":1,\"bin_size\":true},\"offset\":0,\"limit\":80,\"sort\":\"\",\"session_id\":\"3dcfe71efba0403ba454cef4d390f1fb\"},\"id\":\"r105\"}");
get3.setHeader("Content-Type", "application/json");
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
get3.setEntity(entity);
trustAll();
HttpClient client = new DefaultHttpClient();
responseBody3 = client.execute(get3, responseHandler);
My logcat error,
raise SessionExpiredException(\"Session expired\")\nSessionExpiredException: Session expired\n", "type": "client_exception"}}}
Note: My login URL executes correctly.But I cannot re-use my session id for other URL`s.
any body help me?
I have done this for downloading apk file from https url, you can modify according to your requirement
STEP 1: Created an instance of DefaultHttpClient in the first Activity when connection established.
public static DefaultHttpClient httpClient;
STEP 2: For the first time connection
URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
xr.parse(new InputSource(url.openStream()));
STEP 3: Now for all further connections, used the same httpClient For example in the next activity:
URL url=new URL(urlToHit);
HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing
get3.setHeader("Cookie:","session_id=3dcfe71efba0403ba454cef4d390f1fb");
That should be
get3.setHeader("Cookie","session_id=3dcfe71efba0403ba454cef4d390f1fb");
I'm trying to use cookies to hold my session on my Android app, but it seems I'm getting something wrong, because I never receive the expected response from my server.
At first I have a login routine that runs as expected and return all expected data.
My login request:
HttpContext httpContext = new BasicHttpContext();
HttpResponse response;
HttpClient client = new DefaultHttpClient();
String url = context.getString(R.string.url_login);
HttpPost connection = new HttpPost(url);
connection.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair(PARAM_LOGIN,params[0]));
nameValuePair.add(new BasicNameValuePair(PARAM_PASSWORD,params[1]));
connection.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
response = client.execute(connection,httpContext);
data = EntityUtils.toString(response.getEntity());
After I've my response I just make what ever I need with the data and then things start to fall a part. Because now I'm just trying to call my server in the same AsyncTask to test if my cookies got properly saved on my HttpContext.
At first I've just called my URL without any change, just reusing my current HttpContext:
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
HttpResponse response = client.execute(httpPost, httpContext);
Since this test fails I tested to add my cookie value on my HttpPost header:
httpPost.addHeader(context.getString(R.string.domain),PHPSESSID+"="+cookieID+";");
Then I tried creating a new HttpContext and force the COOKIE_STORE:
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie(PHPSESSID, cookieID);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse response;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
response = client.execute(connection,localContext);
All fails, and I've already confirmed that when I first receive my login response I got the data expected from the cookies as can see below:
List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
for (Cookie cookie: cookies){
Log.i("Cookie Value",cookie.toString());
/*
Prints:[[version: 0][name: PHPSESSID][value: 2ebbr87lsd9077m79n842hdgl3][domain: mydomain.org][path: /][expiry: null]]
*/
}
I've already searched on StackOverflow and I've found a ton of solutions that doesn't really worked for me, will share all solutions I've already tried:
Android: Using Cookies in HTTP Post request
HttpPost request with cookies
Sending cookie with http post android
Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request
As I told you, here you are this piece of code in order to make httpPost to a server developed in Spring MVC, with an API REST. Please, consider to build your request on this way:
Please, pay attention to the comments. You should adapt it to your case ;). You can also enclose this code into a method or whatever you prefer.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("yourPath");
//NameValuePairs is build with the params for your request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
CookieStore cookieStore = new BasicCookieStore();
//cookie is a variable that I stored in my shared preferences.
//You have to send in it every request
//In your case, JSESSIONID should change, because it's for Java.
//Maybe it could be "PHPSESSID"
BasicClientCookie c = new BasicClientCookie("JSESSIONID", cookie);
//JSESSIONID: same comment as before.
httppost.setHeader("Cookie", "JSESSIONID="+cookie);
cookieStore.addCookie(c);
((AbstractHttpClient)httpclient).setCookieStore(cookieStore);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
I hope this helps!! It was hard to find it among "old" projects :)
I need to use httpclient to connect to a webpage (Apache) running PHP scripts which is protected with .htaccess authentication.
I've been reading questions and answers (in here and other places) for an hour now, and none of the sultions is working for me. Either the methods people are using in classes like Base64.java does not exist, or the parameters are wrong.
I'm connecting to normal (non-protected webpages like this):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("date", cDate));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
But this, naturally, doesn't help when the page is protected. So how can I, in the easiest way, pass my username and password to the connection?
You can get a Base64 here: http://iharder.sourceforge.net/current/java/base64/.
I usually do something like following for authentication:
StringBuilder authentication = new StringBuilder().append("dogT4g").append(":").append("petTheDog5");
String result = Base64.encodeBytes(authentication.toString().getBytes());
httppost.setHeader("Authorization", "Basic " + result);
Hope that solves your problem.
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);
I needed to send some XML to a webservices and I was able to do it with a normal StringEntity because it was just text but now I need to attach an image to it as well. I tried doing it with a MultipartEntity but I couldn't get it working with just the XML.
// Working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
HttpEntity entity = new StringEntity(writer.toString());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
// not working
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost doc = new HttpPost("http://mywebservices.com");
// no difference when removing the BROWSER_COMPATIBLE
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("xml", new StringBody(writer.toString()));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
And is there a way I could see the MIME that is being send?
You simply forgot:
httppost.setEntity(entity);
By the way, it's probably good form to set the Content-Type of your parts, e.g.:
entity.addPart("xml", new StringBody(writer.toString(),"application/xml",Charset.forName("UTF-8")));
As far as seeing what's being sent, see http://hc.apache.org/httpcomponents-client-ga/logging.html (especially "wire logging") for the HttpClient logging features, and
this question for how to get it working on Android.
Another way to see what's being sent is to set up your own "server" to receive the request. You can do this on a Unix-like system with netcat. The command-line
nc -l 1234
starts a server listening on port 1234, and will echo whatever is received.
If that "server" is on a machine 10.1.2.3, you can just use a new HttpPost("http://10.1.2.3:1234") to send the message there.
I have a similar problem but I'm sending the multipart with user/pass to a acegi security system, it works with this:
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
But not with this:
try {
for (NameValuePair param : params) {
multientity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(encoding))));
}
request.setEntity(multientity);
}