I'm attempting to do basic auth with Apache HTTPClient 4.x using the example from the site, the only change being that I've extracted some details out into constants, however I'm not getting the results I was hoping for.
Namely, with the logging turned up to debug, I'm getting: "DEBUG main client.DefaultHttpClient:1171 - Credentials not found", followed by a 401 error from the server.
I've manually validated that the credentials I've configured are correct, and the "Credentials not found" message leads me to believe the credentials were never passed in the request.
Any thoughts on what I might be doing wrong?
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(API_HOST, API_PORT),
new UsernamePasswordCredentials(API_USERNAME, API_PASSWORD));
HttpGet httpget = new HttpGet(API_TEST_URL);
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
Are you sure the AuthScope is set correctly? Try setting it like this just to see if the problem is there
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT)
Related
I am attempting a GET request to another API to get a json response.
When I make the request with the code below, I am getting HTTP 504 Error (Gateway timeout error).
However, when I tried it through rest client tool, the request does not throw any error.
How do I increase the time gap in my code to avoid the timeout error?
This is how the call looks like:
HttpClient httpClient = getBasicAuthDefaultHttpClient();
String url= "http://XXXXX";
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("id", id);
httpGet.addHeader("secret", secret);
httpGet.addHeader("network_val", networkval);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
ObjectMapper objectMapper = new ObjectMapper();
restInfo = objectMapper.readValue(entity.getContent(), MyClass.class);
} else {
logger.error("Call to API failed: response code = {}", response.getStatusLine().getStatusCode());
}
Please note:
Could this be something to do with 'https'?
When I try with 'http' through my Insomnia REST Client I get the ERROR: error: Failure when receiving data from the peer.
https works fine without any error (https://XXXXX)
This is what I tried.
public HttpClient getBasicAuthDefaultHttpClient() {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user,
password);
provider.setCredentials(AuthScope.ANY, creds);
//Fix to avoid HTTP 504 ERROR (GATEWAY TIME OUT ERROR)
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder.setConnectTimeout(30 * 1000);
requestBuilder.setConnectionRequestTimeout(30 * 1000);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setDefaultCredentialsProvider(provider).build();
return builder.build();
}
I'm trying to download a file from a Sharepoint repository (where I have regularly access from my corporate network) and I'm doing it from JAVA 7 program.
I'm using the following code, just got from stackoverflow, but my download attempt is failing with error : HTTP/1.1 403 Forbidden
For sake of completeness, the same request is also failing if a try from POSTMAN then it looks due something related to authentication schema.
Of course I have no problem when accessing from common WEB browsers.
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY),
new NTCredentials("username", "password", "usernamestring", "passwordstring"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
try {
HttpGet httpget = new HttpGet("https://xxx.sharepoint.com/sites /YYYYY/default.aspx");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}
I use the following command to generate web service client files for java.
wsimport -keep http://test.com/test?wsdl -xauthfile auth.txt
The following was in auth.txt
http://user:password#ip:port//path
But, the password was having special characters like abcw#sdsds.
So I was getting wrong format error. So I have encoded password like abcw%40sdsds. But, now got authentication error due to wrong password because of parsing.
Is there any ways to handle this scenario ?
After checking online I found this bug was actually fixed in the latest version. But I still get the same issue. You can refer to the following links for information on the bug.
https://github.com/javaee/metro-jax-ws/issues/1101
So I finally made custom HTTP request with NTLM authentication using HTTP Client in Java.
String bodyAsString = ""; //Provide Input SOAP Message
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("UserName", "Password", "Host", "Domain"));
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
HttpPost post = new HttpPost("URL"); //Provide Request URL
try
{
StringEntity input = new StringEntity(bodyAsString);
input.setContentType("text/xml; charset=utf-8");
post.setEntity(input);
post.setHeader("Content-type", "text/xml; charset=utf-8");
post.setHeader("SOAPAction", ""); //Provide Soap action
org.apache.http.HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
return EntityUtils.toString(responseEntity);
}
}
I got the above solution from the following github link
https://github.com/sujithtw/soapwithntlm
net developer and dont know about android. could you please help me to fix this code
Exception: android.os.networkmainthreadException on
client.execute(get1)
try
{
HttpGet get1 = new HttpGet ("http://www.google.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get1);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
}
catch(Exception e )
{
urlview.setText( "hi bug"+ e.toString());
}
You are doing network operation on UI thread which in not allowed in android version >=3.0 So use AsyncTask
Does anyone have a good tutorial on how to write a java or javafx cURL application? I have seen tons of tutorials on how to initiate an external call to say like an XML file, but the XML feed I am trying to retrieve calls for you to submit the username and password before being able to retrieve the XML feed.
What are you trying to accomplish? Are you trying to retrieve a XML feed over HTTP?
In that case I suggest you to take a look at Apache HttpClient. It offers similair functionality as cURL but in a pure Java way (cURL is a native C application). HttpClient supports multiple authentication mechanisms. For example you can submit a username/password using Basic Authentication like this:
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
Check the website for more examples.