Setup HttpClient proxy to access REST URL on EC2 - amazon-ec2

I have an EC2 image running and hosting a REST service accessible from a URL. The following is what I did:
ssh -i <ec2-certificate> D port user#ec2-host
Setup proxy in the firefox web browser and typed in the url http://ec2-host:port/demo/workflow/lists/demo_workflow
It works fine.
Now I need to send the GET method using a Java program; below is my code:
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://ec2-host:port/demo/workflow/lists/demo_workflow");
HostConfiguration config = client.getHostConfiguration();
config.setProxy(proxyHost, port);
client.setHostConfiguration(config);
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
String response = method.getResponseBodyAsString();
System.out.println("Response = " + response);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
But now I run into the exceptions below. Any tips?
010-08-11 16:46:34,781 INFO
[HttpMethodDirector] I/O exception
(org.apache.commons.httpclient.NoHttpResponseException)
caught when processing request: The
server 184.72.46.209 failed to respond
2010-08-11 16:46:34,781 INFO
[HttpMethodDirector] Retrying request
org.apache.commons.httpclient.NoHttpResponseException:
The server [ec2-host] failed to
respond at
org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1976)
at
org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735)
at
org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098)
at
org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at
org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at
org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at
org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at ....[where my code throws
exception when invoking
client.executeMethod(config)]

Related

Calling Web API method in postman

I am trying to call the following Web API method in Postman:
public HttpResponseMessage GetAllNotifications(HttpRequestMessage request, String Name)
{
HttpResponseMessage response = null;
try
{
List<ExpandoObject> res = _userProcess.GetAllNotifications(Name);
response = request.CreateResponse<List<ExpandoObject>>(HttpStatusCode.OK, res);
}
catch (Exception ex)
{
response = request.CreateResponse<string>(HttpStatusCode.BadRequest, "Unable to process your request Please contact administration");
throw new DataException(ex.Message.ToString());
}
return response;
}
Any advice appreciated.
Just run your Project in localhost and copy the Url from the Browser and add
your Api name , Example if the Project runs with an url like : https://localhost:3000/api/values
Just change the url with your api name in place of "values"
https://localhost:3000/api/GetAllNotifications and now paste this url in postman and set get method and click on send make sure your project is running in the same localhost port Number.

Vertx client gets clientabort exception

I am geting clientabort sockettimeout read exception at server side while invoking a rest service through https client inside vertx application. If i invoke a http setvice, it works fine though.
I get 200 ok in vertx and do not get any data back. And also i get connection was closed error in vertx.
Any idea why it happens. Help appreciated.
Code:
final HttpClient httpClient1 = vertx.createHttpClient(
new HttpClientOptions()
.setDefaultHost("localhost")
.setDefaultPo‌​rt(8443)
.setSsl(true‌​)
.setKeepAlive(true)‌
​.setMaxPoolSize(100)‌​
.setTrustAll(true)
);
‌​HttpClientRequest req = httpClient1.request(HttpMethod.POST, "/api/test/");
req.headers()
.set("Content-Length","10000000")‌​
.set("Content-Type",‌​"application/json")
.‌​set("Cache-Control", "no-transform, max-age=0");
Buffer body=Buffer.buffer("Hello World");
req.write(body);
That's not the way to send a request.
Hope working example may help you.
Server:
final Vertx vertx = Vertx.vertx();
vertx.createHttpServer().requestHandler((c) -> {
c.bodyHandler(b -> {
System.out.println(b.toString());
});
c.response().end("ok");
}).listen(8443);
Client:
final HttpClient client = vertx.createHttpClient(
new HttpClientOptions()
.setDefaultHost("localhost")
.setDefaultPort(8443));
client.request(HttpMethod.POST, "/", (r) -> {
System.out.println("Got response");
}).putHeader("Content-Length", Integer.toString("Hello".length()))
.write("Hello").end();
Two important notes: you must end .request() with .end() and you must set Content-Length correctly.

Enable authenticator manually

Currently my client authenticates request only on case of 401 response:
this.client.authenticator(new okhttp3.Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credentials = authenticator.getCredentials();
if (credentials.equals(response.request().header("Authorization"))) {
throw new TraversonException(401, "Unauthorized", response.request().url().toString());
} else {
defaultHeader("Authorization", credentials);
Request.Builder newRequest = response.request().newBuilder()
.headers(Headers.of(defaultHeaders));
return newRequest.build();
}
});
But I'd like to change this behavior and be able to call it either manually or auto per first call? Is it possible somehow?
If the authentication is predictably required and not related to a proxy, then the solution is to implement an Interceptor instead of Authenticator.
OkHttpClient.Builder clientBuilder = ...;
clientBuilder.networkInterceptors().add(0, myInterceptor);
client = clientBuilder.build();
Example Interceptor https://github.com/yschimke/oksocial/blob/48e0ca53b85e608443eab614829cb0361c79aa47/src/main/java/com/baulsupp/oksocial/uber/UberAuthInterceptor.java
n.b. There is discussion around possible support for this usecase in https://github.com/square/okhttp/pull/2458. One issue with current Authenticator API is that it assumes a Response from the failed (401) request.

HTTPS support on Windows Phone 8 HttpClient

I am trying to use Nuget Http client library:
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("UserAgent", "Windows 8 app client");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == HttpStatusCode.OK)
return await response.Content.ReadAsStringAsync();
else
throw new Exception("Error connecting to " + url +" ! Status: " + response.StatusCode);
When I make a https request to a site that has self-signed certificate, I get 404 error. How do I set a flag to allow invalid SSL certificate in the client?

AJAX 504 when calling ASP.NET Web API

My AJAX call is returning a 504 error when calling an ASP.NET Web API action.
More info:
Here's my API action:
public HttpResponseMessage Get(string fileName, int feedID)
{
try
{
// create file...
return new HttpResponseMessage { Content = new StringContent("Complete."), StatusCode = HttpStatusCode.OK };
}
catch (Exception ex)
{
Log.WriteError(ex);
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("An error has occurred.")
});
}
}
Here's my AJAX call:
$.ajax({
url: url,
type: 'GET',
success: function () {
$("#lblProgressDownload").hide();
window.open("Previews/" + fileName);
},
error: function (xhr, status, error) {
$("#lblProgressDownload").hide();
alert("Error downloading feed preview: " + error);
}
});
I get a 504 error (viewed in fiddler/ chrome console) when the file takes too long to create. The "error" parameter in the error callback doesn't return anything.
I only get the 504 error when it's hosted - on my dev it works fine.
How do I prevent this 504 error?
Note, I already tried changing the executionTimeout property in my web.config, as well as the ajax timeout. Neither worked.
HTTP error 504 is a gateway timeout:
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI [...] in attempting to complete the request.
I suspect that means there is a proxy or gateway somewhere between you and the production server, but not your dev server, which is why it fails on the one but not the other.
Your choice is either to make your server code fast enough that it doesn't trigger the timeout, or get whoever is running the proxy server to relax their timeout restrictions (assuming it's something that you or your company controls).

Resources