proxy for the REST - rest

I have a method in which sending XML(byte array) through REST. I set the global properties of a test proxy (CCProxy). In the application CCProxy log I have nothing. What did I do wrong?
url = "https://myurl/api/Storage/Init";
SSLContext sc = createSslContext();
Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}).build();
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "192.168.11.64");
System.setProperty("http.proxyPort", "808");
System.setProperty("https.proxyHost", "192.168.11.64");
System.setProperty("https.proxyPort", "808");
// client.property("http.proxy.server.uri", "192.168.11.64");
// client.property("http.proxy.server.port", "808");
// client.property("https.proxy.server.uri", "192.168.11.64");
// client.property("https.proxy.server.port", "808");
javax.ws.rs.core.Response response = client.target(url).request(MediaType.APPLICATION_JSON)
.post(Entity.entity(doc, MediaType.APPLICATION_XML));
setting CCProxy
The second question, how to set the proxy only for a particular method? I tried something like this but it did not work.
client.property("http.proxy.server.uri", "192.168.11.64");
client.property("http.proxy.server.port", "808");
Update: After the changes as suggested by CWasp
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
HttpClient httpClient = HttpClientBuilder.create()
.setProxy(new HttpHost("192.168.11.64", 808))
.setDefaultCredentialsProvider(credProvider).setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setSSLContext(sslContext)
.build();
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
client = new ResteasyClientBuilder().httpEngine(engine).build();

Try this if proxy authentication required
For Jersey 2.x:
ClientConfig config = new ClientConfig();
config.connectorProvider(new ApacheConnectorProvider());
config.property(ClientProperties.PROXY_URI, "http://" + PROXY_HOST + ":" + PROXY_PORT);
config.property(ClientProperties.PROXY_USERNAME, PROXY_USER);
config.property(ClientProperties.PROXY_PASSWORD, PROXY_PASS);
JerseyClient client = new JerseyClientBuilder()
.withConfig(config)
.build();
For Resteasy:
Credentials credentials = new UsernamePasswordCredentials(PROXY_USER, PROXY_PASS);
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), credentials);
HttpClient httpClient = HttpClientBuilder.create()
.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT))
.setDefaultCredentialsProvider(credProvider)
.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
.build();
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
ResteasyClient client = new ResteasyClientBuilder()
.httpEngine(engine)
.build();

Related

VSTS Web Api gives 403 unauthoratative response

I have created a native app in Azure using App Registration and added required permissions for VSTS Agent
Now, I am able to login using oauth authentication with "ADAL" and able to get the token but when trying to access the web api request it gives Http 403 Response
Here is the code example below
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
HttpResponseMessage res = client.GetAsync(webapiURL).Result;
}
Please let me know what i am missing
thanks in advance
Seems it's an authentication issue, Just check the value of authHeader.
You can reference below samples for the authentication with header:
Sample 1- auth-samples here ;
Sample 2 - REST API
Post the auth sample as reference here:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
namespace DeviceProfileSample
{
public class Program
{
//============= Config [Edit these with your settings] =====================
internal const string vstsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS account; NOTE: This must use HTTPS
internal const string clientId = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1"; //update this with your Application ID from step 2.6 (do not change this if you have an MSA backed account)
//==========================================================================
internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Static value to target VSTS. Do not change
public static void Main(string[] args)
{
AuthenticationContext ctx = GetAuthenticationContext(null);
AuthenticationResult result = null;
try
{
DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync(VSTSResourceId, clientId).Result;
Console.WriteLine("You need to sign in.");
Console.WriteLine("Message: " + codeResult.Message + "\n");
result = ctx.AcquireTokenByDeviceCodeAsync(codeResult).Result;
var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken);
ListProjects(bearerAuthHeader);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Something went wrong.");
Console.WriteLine("Message: " + ex.Message + "\n");
}
}
private static AuthenticationContext GetAuthenticationContext(string tenant)
{
AuthenticationContext ctx = null;
if (tenant != null)
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
else
{
ctx = new AuthenticationContext("https://login.windows.net/common");
if (ctx.TokenCache.Count > 0)
{
string homeTenant = ctx.TokenCache.ReadItems().First().TenantId;
ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant);
}
}
return ctx;
}
private static void ListProjects(AuthenticationHeaderValue authHeader)
{
// use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "VstsRestApiSamples");
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Authorization = authHeader;
// connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result;
// check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\tSuccesful REST call");
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
}
}
}
}
Aren't you missing what authentication,
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", token)));
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(vstsCollectionUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials)
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
var responseStream = await response.Content.ReadAsStreamAsync();
}
I hope this helps.

Using HTTPClientParams for HttpClient 4.5

I have a code with HttpClient 3.x which uses HTTPClientParams.
HttpClientParams params = new HttpClientParams();
params.setVersion(HttpVersion.HTTP_1_1);
params.setContentCharset(ENCODING);
try {
URI uri = new URI(some-resource);
int port = uri.getPort();
Protocol protocol = null;
if(port == -1){
if(uri.getScheme().compareToIgnoreCase("http") == 0){
port = 80;
protocol = Protocol.getProtocol("http");
}
else if(uri.getScheme().compareToIgnoreCase("https") == 0){
port = 443;
protocol = Protocol.getProtocol("https");
}
}
Protocol.registerProtocol(uri.getScheme(), protocol);
HttpConnectionManager manager = new SimpleHttpConnectionManager();
HttpClient client = new HttpClient(manager);
client.setParams(params);
I have verified that for HTTPClient 4.5 there are not HTTPParam method. How can I upgrade the same? Are there any alternatives?
Please have a look at RequestConfig class
This code should be roughly equivalent to your code above
CloseableHttpClient client = HttpClientBuilder.create()
.setConnectionManager(new BasicHttpClientConnectionManager())
.setDefaultRequestConfig(RequestConfig
.custom()
// Add custom request parameters
.build())
.build();
URI uri = new URI(some - resource);
HttpGet httpGet = new HttpGet(uri);
httpGet.setProtocolVersion(HttpVersion.HTTP_1_1);
try (CloseableHttpResponse response1 = client.execute(httpGet)) {
EntityUtils.toString(response1.getEntity(), Charset.forName(ENCODING));
}

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

C# WebApi HttpClient Unauthorized

I have an issue about webapi2 and Authorization.
If I call web api with the old .Net 2.0 client (WebClient) there are not problems and the code is here:
//old 2.0 client
using (WebClient oldClient = new WebClient())
{
oldClient.UseDefaultCredentials = true;
oldClient.Credentials = CredentialCache.DefaultCredentials;
oldClient.Headers[HttpRequestHeader.ContentType] = "application/json";
oldClient.Headers[HttpRequestHeader.Accept] = "application/json";
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = 2147483644;
ASCIIEncoding encoding = new ASCIIEncoding();
string objectToSendJson = javaScriptSerializer.Serialize(objectToSend);
byte[] objectToSendByte = encoding.GetBytes(objectToSendJson);
byte[] serviceOutput = oldClient.UploadData(uri + actionController, "POST", objectToSendByte);
string jsonStr = Encoding.UTF8.GetString(serviceOutput);
toReturn = JsonConvert.DeserializeObject<T>(jsonStr);
return toReturn;
}
but if I use the new 4.5 HttpClient WebApi return me Unauthorized
and the code is here:
HttpClientHandler httpWebApiClienthandler = new HttpClientHandler
{
UseDefaultCredentials = true,
Credentials = CredentialCache.DefaultCredentials,
};
System.Net.Http.HttpClient newHttpClient = new System.Net.Http.HttpClient(httpWebApiClienthandler)
//new 4.5 client
JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
if (objectToSend == null)
throw new Exception("object to send is null");
HttpContent httpContent = new ObjectContent<object>(objectToSend, jsonFormatter);
httpContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
response = newHttpClient.PostAsync(actionController, httpContent).Result;
Any help is highly appreciated.

cannot instantiate the type httpclient in android

Am getting an error with the following line of code
HttpClient Client= new HttpClient.
I have tried rewriting it as HttpClient Client= new DefaultHttpClient. but it solves the problem and creates a new error with other methods
.
Here is a glimpse of my code
protected static MDSResult doExecute(Context ctx, HttpMethod method){
HttpClient client = new HttpClient();
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(ctx);
MDSResult response = null;
// If there's a proxy enabled, use it.
String proxyHost = preferences.getString(
Constants.PREFERENCE_PROXY_HOST, "");
String sProxyPort = preferences.getString(
Constants.PREFERENCE_PROXY_PORT, "0");
boolean useSecure = preferences.getBoolean(
Constants.PREFERENCE_SECURE_TRANSMISSION, false);
int proxyPort = 0;
try {
if (!"".equals(sProxyPort))
proxyPort = Integer.parseInt(sProxyPort);
} catch(NumberFormatException e) {
Log.w(TAG, "Invalid proxy port: " + sProxyPort);
}
if (!"".equals(proxyHost) && proxyPort != 0) {
Log.i(TAG, "Setting proxy to " + proxyHost + ":" + proxyPort);
HostConfiguration hc = new HostConfiguration();
hc.setProxy(proxyHost, (int)proxyPort);
client.setHostConfiguration(hc);
}
// execute the Http/https method
try {
if(useSecure){
ProtocolSocketFactory ssl = new SimpleSSLProtocolSocketFactory();
Protocol https = new Protocol("https", ssl, 443);
Protocol.registerProtocol("https", https);
}
int status = client.executeMethod(method);
Log.d(TAG, "postResponses got response code " + status);
char buf[] = new char[20560];
Reader reader = new InputStreamReader(
method.getResponseBodyAsStream());
int total = reader.read(buf, 0, 20560);
String responseString = new String(buf);
Log.d(TAG, "Received from MDS:" + responseString.length()+" chars");
Gson gson = new Gson();
response = gson.fromJson(responseString, MDSResult.class);
}
You want DefaultHttpClient, not HttpClient like you mentioned. HttpClient is abstract so cannot be instantiated.
HttpClient client = new DefaultHttpClient();
What is the error with the other methods when you use that ?
Also why not use HttpURLConnection ? I find it much more reliable.