Java NTLM Athentication for sharepoint online services getting 401 error - java

i tried the below code for getting lists from a clients sharepoint service (2013) its an https (invalid certificcate),i have downlaoded the same certiite and instaleld in cacets.everytime im getting the below response
try{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
DefaultHttpClient httpClient = new DefaultHttpClient(params);
httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new
NTCredentials("username", "passwrd", "host", "domain"));
HttpPut request = new HttpPut("https://domain/_api/get..");
request.setHeader("Content-Type", "application/json;odata=verbose");
request.setHeader("Accept", "application/json;odata=verbose");
System.out.println(httpClient.execute(request));
}catch(Exception e){
throw e;
}
RESPONSE
HTTP/1.1 401 Unauthorized [Server: Microsoft-IIS/8.5,
SPRequestGuid: 6ecb4d9f-9884-c0ba-7e4e-eed562a7e616,
request-id: 6ecb4d9f-9884-c0ba-7e4e-eed562a7e616,
X-FRAME-OPTIONS: SAMEORIGIN,
SPRequestDuration: 4,
SPIisLatency: 0,
WWW-Authenticate: NTLM,
X-Powered-By: ASP.NET,
MicrosoftSharePointTeamServices: 15.0.0.5172,
X-Content-Type-Options: nosniff,
X-MS-InvokeApp: 1;
RequireReadOnly,
Date: Thu,
30 Apr 2020 10:02:57 GMT,
Content-Length: 0] org.apache.http.conn.BasicManagedEntity#679b62af

I got the solution
it because of the port and hostname

Related

Encoding issue Android / REST /JSON

i´m trying to solve encoding issue for response (json) from simple rest service in my app for about one day now, no more ideas..
when i open response in restclient, getting correct result:
Status Code: 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 270
Content-Type: application/json; charset=utf-8
Date: Wed, 13 Apr 2016 09:26:39 GMT
Keep-Alive: timeout=15, max=100
Server: Apache
Vary: Accept-Encoding
response:
{"reqStatus": 1,
"articles": [
{
"articleId": "1",
"articleName": "Schüssel 18cm",
"articlePrice": "34.50",
"articleDate": "2016-03-15 17:34:00",
"userZip": "76879",
"userCity": "Ottersheim",
"articleImages": [ ...
for inputstream getting that:
{"reqStatus":1,"articles":[{"articleId":"1","articleName":"Sch\u00fcssel 18cm","articlePrice":"34.50","articleDate":"2016-03-15 17:34:00","userZip":"76879","userCity":"Ottersheim","articleImages":[ ...
code for request:
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("POST");
if (headers!=null&&headers.length>0){
for (int i=0;i < headers.length;i++){
urlConnection.setRequestProperty(headers[i][0].toString(), headers[i][1].toString());
}
}
urlConnection.connect()
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
BufferedReader streamReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
return new JSONObject(inputStr);
}
any ideas?

How to get response code of httpPut in java

I am using httpPut to java and I want to get the response code after I execute the command. What it gives me which is "response body" is:
HTTP/1.1 200 OK [Cache-Control: no-cache, no-store, must-revalidate, Pragma: no-cache, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json, Transfer-Encoding: chunked, Server: Jetty(8.1.8.v20121106)]
But I only want 200! not the whole thing. Any help?
This is my code by the way:
String url = "http://localhost:80/api/clients/";
String clientID = "1234";
httpclient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(url + clientID);
putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
putRequest.setHeader("Charset", "UTF-8");
System.out.println(putRequest);
// Add your data
putRequest.setEntity(new StringEntity(clientID, "UTF-8"));
HttpResponse responseBody = httpclient.execute(putRequest);
HTTPResonse having a method called getStatusLine() which return StatusLine Object.
And StatusLine have a method getStatusCode()
So, all you need to write is
HttpResponse responseBody = httpclient.execute(putRequest);
int resultCode = responseBody.getStatusLine().getStatusCode();//200 in your case
responseBody.getStatusLine().getStatusCode() should give you the responsecode of your request.

Error "HTTP/1.1 401 Unauthorized" with basic authentication in android - EWS 2010

I refer to this link to request to the server. The problem is sometime (not always, about 20% - 30%, means sometime I can get successful response), I got the 401 error and server response basic authorization challenge expected, but not found.
Here is my code:
HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor()
{
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException
{
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null)
{
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null)
{
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
Here is my authentication:
HttpPost httpPost = new HttpPost(SERVER_AUTH_URL);
httpPost.setHeader("Content-type", "text/xml; charset=utf-8");
httpPost.setHeader("Keep-Alive", "300");
httpPost.setHeader("Connection", "Keep-Alive");
StringEntity se = new StringEntity(myRequest, "UTF-8");
httpPost.setEntity(se);
se.setContentType("text/xml");
se.setContentEncoding("gzip,deflate");
//add preemptiveAuth
client.addRequestInterceptor(preemptiveAuth, 0);
//Set the proxy
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
client.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
client.setRoutePlanner(routePlanner);
List<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthPolicy.BASIC);
authPrefs.add(AuthPolicy.NTLM);
authPrefs.add(AuthPolicy.DIGEST);
client.getParams().setParameter("http.auth.scheme-priority", authPrefs);
CredentialsProvider credProvider = new BasicCredentialsProvider();
// client.getParams().setParameter("http.auth.scheme-priority",
// authPrefs);
credProvider.setCredentials(AuthScope.ANY,
new NTCredentials(getUsername(), getPassword(),
"", getDomain()));
Log.d(TAG, "repair excute");
client.setCredentialsProvider(credProvider);
HttpResponse response = client.execute(httpPost);
Log.d(TAG, "has excute");
From the comment code, you can see I tried many ways, but the error wasn't disappear. Here is logcat say:
05-02 10:28:21.724: D/dalvikvm(1169): GC_FOR_MALLOC freed 11259 objects / 457352 bytes in 43ms
05-02 10:28:22.384: D/MainActivity(1169): repair excute
05-02 10:28:22.744: D/dalvikvm(1169): GC_FOR_MALLOC freed 11481 objects / 447264 bytes in 67ms
05-02 10:28:22.894: D/dalvikvm(1169): GC_FOR_MALLOC freed 1078 objects / 83928 bytes in 76ms
05-02 10:28:22.894: I/dalvikvm-heap(1169): Grow heap (frag case) to 3.833MB for 87396-byte allocation
05-02 10:28:23.034: D/dalvikvm(1169): GC_FOR_MALLOC freed 58 objects / 3336 bytes in 143ms
05-02 10:28:23.124: W/DefaultRequestDirector(1169): Authentication error: basic authorization challenge expected, but not found
05-02 10:28:23.124: D/MainActivity(1169): has excute
05-02 10:28:23.124: E/MainActivity(1169): response error: HTTP/1.1 401 Unauthorized
So, please tell me where is my problem. Thanks in advance.
Update: the target server is Exchange Web Service 2010. For some reason, I don't want to use EWS API, I made my own xml request to connect to the server (this xml request works properly).
And here is the response header from server
When request failed:
Server Microsoft-IIS/7.5
WWW-Authenticate Negotiate
WWW-Authenticate NTLM
X-Powered-By ASP.NET
Date Fri, 25 May 2012 03:47:57 GMT
Content-Length 0
When request success the first time:
Cache-Control private
Transfer-Encoding chunked
Content-Type text/xml; charset=utf-8
Server Microsoft-IIS/7.5
Set-Cookie exchangecookie=1d9d9b1d21064035ad375c8aecde2168; expires=Sat, 25-May-2013 04:00:46 GMT; path=/; HttpOnly
X-AspNet-Version 2.0.50727
X-Powered-By ASP.NET
Date Fri, 25 May 2012 04:00:45 GMT
and the second time:
Cache-Control private
Transfer-Encoding chunked
Content-Type text/xml; charset=utf-8
Server Microsoft-IIS/7.5
X-EwsPerformanceData RpcC=4;RpcL=0;LdapC=0;LdapL=0;
X-AspNet-Version 2.0.50727
X-Powered-By ASP.NET
Date Fri, 25 May 2012 04:00:47 GMT
The cookie is my problem, isn't it?
I was struggling with Android HTTP basic last week. I have tried maybe 3 or 4 different ways of doing it and always I found some problem. Right now the only way I managed to make it work was the simplest way.
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
Header header = new BasicScheme().authenticate(credentials, mHttpRequest);
mHttpRequest.addHeader(header);
That worked for me with AndroidHttpClient.
Edit:
This is my full source code
https://gist.github.com/2642692
It's based on
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/

Java - problems with REST client while sending an HTTP request

I am trying to send a GET request to a REST server using Java.
This is the code with some debugging.
URL url = new URL(request);
System.out.println("request url: " + url.toString());
System.out.println("method: " + httpMethod);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(httpMethod);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
OutputStream os = connection.getOutputStream();
os.flush();
String response = os.toString();
System.out.println("response: " + response);
if (response.length() == 0)
{
throw new MyException("the response is empty");
}
This is the output:
request url: http://www.example.com/api.php/getToken/?api_ver=1&token=&api_key=bf8de053d9b6c540fb12195b4ac1602b0a71788c&sig=e00a59747afc7232207d40087e3765a5
method: GET
response:
com.example.api.client.MyException: the response is empty
As you can see, the response is empty.
But if I try and copy and paste the URL in Firefox I get this output
{"error":220}
and this header:
HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 11:55:29 GMT
Server: Apache
Cache-Control: max-age=0
Expires: Mon, 15 Nov 2010 11:55:29 GMT
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 33
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
Can you see what it is wrong? How could I debug this code further?
Any help would be very much appreciated.
I think you do not use HttpURLConnection properly (there is no connect()).
Maybe study this example.

HttpClient unable to 302 this link?

I found a URL that httpclient doesn't seem to be handling redirects on:
http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
should 302 to:
http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
when I look at the headers in the browser everything looks good:
HTTP/1.1 302 Moved Temporarily
Content-Type: text/html; charset=UTF-8
Location: http://www.mtv.com/news/articles/1647243/20100907/story.jhtml
Content-Length: 258
Date: Wed, 08 Sep 2010 18:40:21 GMT
Expires: Wed, 08 Sep 2010 18:40:21 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
Server: GSE
Set-Cookie: PREF=ID=024209255b405b06:TM=1283971221:LM=1283971221:S=AG-13_7Cjg_EqlRY; expires=Fri, 07-Sep-2012 18:40:21 GMT; path=/; domain=.google.com
Connection: close
However httpclient doesn't seem to give me the final URL. Here is the code I was using
HttpHead httpget = null;
HttpHost target = null;
HttpUriRequest req = null;
String startURL = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGrJk-F7Dmshmtze2yhifxRsv8sRg&url=http://www.mtv.com/news/articles/1647243/20100907/story.jhtml";
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetcher.emptyCookieStore);
httpget = new HttpHead(startURL);
HttpResponse response = httpClient.execute(httpget, localContext);
Header[] test = response.getAllHeaders();
for(Header h: test) {
logger.info(h.getName()+ ": "+h.getValue());
}
target = (HttpHost) localContext.getAttribute( ExecutionContext.HTTP_TARGET_HOST );
req = (HttpUriRequest) localContext.getAttribute( ExecutionContext.HTTP_REQUEST );
// STILL PRINTS OUT THE GOOGLE NEWS LINK
finalURL = target+""+req.getURI();
Am I doing something wrong? thanks
Found the answer from the httpclient mailing list...
Google doesn't treat a HEAD and GET the same, so the GET redirects with 302 and the HEAD request gives a 200 OK

Categories

Resources