I am using the new Apache HttpClient 4.2 (not the one from Apache Commons).
I need to open up one HttpClient and make multiple requests to the same server. From the documentation, the httpClient should automatically maintain the cookie, and therefore have the multiple requests fall in the same session. However, on the server side, I am debugging thru and see that
HttpSession session = req.getHttpSession(true);
is returning a new HttpSession Object every time.
my client code is like this.
// 1st time
HttpClient httpClient = new DefaultHttpClient();
req.getSession(true).setAttribute(HTTPCLIENT, httpClient);
HttpGet httpget = new HttpGet(redirectUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String content = httpClient.execute(httpget, responseHandler);
// subsequent calls
HttpClient httpClient = getHttpClient(req);
HttpGet httpget = new HttpGet(redirectUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String content = httpClient.execute(httpget, responseHandler);
// supported by the private method
private HttpClient getHttpClient(HttpServletRequest req){
return (HttpClient) req.getSession(true).getAttribute(HTTPCLIENT);
}
did I do anything wrong?
my dumb experiment.
it was because I was mixing up using and by passing the HttpClient on different requests from the same browser (e.g. by passing on .js and .css files). These by passed resources returned a different sessionId to the browser, and subsequently, the browser started using the new sessionId.
Related
I have to implement a Vertx POST request. Via Postman, the request is done as shown in the following picture:
The tricky part is that the server expects the key "upgrade_file" for the body. I could not find out how to do that with Vertx. This is what I have so far:
Buffer bodyBuffer = Buffer.buffer(body); // body is byte[]
HttpClientRequest request = ...
request.handler( response -> ...
request.end(bodyBuffer);
How can I set "upgrade_file" as the key for the body?
Use a WebClient instead of the HTTP client, it provides dedicated support for submitting forms.
WebClient client = WebClient.create(vertx);
or if you already have created an http client:
WebClient client = WebClient.wrap(httpClient);
Then create the form data as map and send the form using a the right content type
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.set("upgrade_file", "...");
// Submit the form as a multipart form body
client.post(8080, "yourhost", "/some_address")
.putHeader("content-type", "multipart/form-data")
.sendForm(form, ar -> {
//do something with the response
});
More example see https://vertx.io/docs/vertx-web-client/java/
If you want to send files, the simplest way is using the sendMultipartForm method of Vertx WebClient.
Create a Multipartform firstly.
MultipartForm form = MultipartForm.create()
.attribute("imageDescription", "a very nice image")
.binaryFileUpload(
"imageFile",
"image.jpg",
"/path/to/image",
"image/jpeg");
Then invoke WebClient.sendMultipartForm(form) to send the request.
The generic Vertx HttpClient is a low-level API, you should searialize the form data into a string or buffer, the format is similar to this example file in Vertx GraphQL testing codes. Then send the buffer to the server side.
I define the httpClient using ModernHttpClient
var httpClient = new System.Net.Http.HttpClient(new NativeMessageHandler());
httpClient.DefaultRequestHeaders.ConnectionClose = true;
And then use the same httpClient instance for several requests
var result = await httpClient.GetAsync("someaddress");
This request fails sometimes but not always with IOException with message.
"EndRead failed". What is the general cause for this exception? Is the connection closed before its done or what? The code is running on Android.
I am new to couchdb and I want to learn about how to connect the couchdb in our gwt server side program. till now, I tried to work on its gui to create database add documents and add fields to it.but i am not able to use it in program. what exactly the way to do it..
I tried some code but didn't got it.
In your GWT you should have something like this in your server. Besides it you should have your DAO for your Entities (erktorp takes place here) and your mechanism for connecting GWT's client with the server (for example RequestFactory).
//Object of your own related with couch db management
CouchDbAccess couchDbAccess = null;
#Inject
public CouchDbManagement(String ddbbUrl, String ddbbName) throws IOException {
HttpClient httpClient;
Builder b;
try {
b = new StdHttpClient.Builder().url(ddbbUrl);
} catch (Exception e) {
e.printStackTrace();
ddbbUrl = "http://admin:sa#localhost:5984";
b = new StdHttpClient.Builder();
}
b.socketTimeout(60000);
String user = getUserFrom(ddbbUrl);
String pass = getPassFrom(ddbbUrl);
b.username(user).password(pass);
httpClient = b.build();
CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
if (initialize && dbInstance.getAllDatabases().contains(ddbbName)) {
dbInstance.deleteDatabase(ddbbName);
dbInstance = new StdCouchDbInstance(httpClient);
}
//If you want Lucene, here is the place
db.createDatabaseIfNotExists();
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
URI dbURI = URI.prototype(DbPath.fromString(ddbbName).getPath());
RestTemplate restTemplate = new RestTemplate(dbInstance.getConnection());
couchDbAccess = new CouchDbAccess(db, dbURI, restTemplate);
}
Couchdb has a restful interface to it's api. Everything is available via url's like
http://localhost:5984/db_name/doc_name
In fact the entire http api is documented in the wiki. Now I am not familiar with gwt but every framework has http libraries and you can use those libraries to make calls to couchdb http endpoints.
A quick google search gave me this resource which may guide you on how to create http requests through gwt.
Recently I was using RestSharp to consume my Restful Resouce. and expected exchanging data with JSon between server and client. Below is my C# code.
var client = new RestSharp.RestClient();
var request = new RestRequest(sUrl,Method.POST);
request.RequestFormat = DataFormat.Json;
request.Timeout = TIME_OUT_MILLISECONTS ;
request.AddHeader("Content-Type", "application/json");
request.AddBody(new { appID = sAppId, loginName = sUserName, password=sPassword });
var response = client.Execute(request);
string s=response.Content;//It is always XML format.
The result is not what I expected for(Json data format), although I had set the RequestFormat Json and add Http header Content-Type. So I decided to use the .Net Reflector to found out What happened in the RestClient.Execute method. Here is the code of the method.
public RestClient()
{
...
this.AddHandler("application/json", new JsonDeserializer());
this.AddHandler("application/xml", new XmlDeserializer());
this.AddHandler("text/json", new JsonDeserializer());
this.AddHandler("text/x-json", new JsonDeserializer());
this.AddHandler("text/javascript", new JsonDeserializer());
this.AddHandler("text/xml", new XmlDeserializer());
this.AddHandler("*", new XmlDeserializer());
...
}
I have some questions about it:
As the RestClient adds many kinds of Content-Type into the HttpWebRequest. Is it right way to build a Request? And I think Maybe that is the reason why Response.Content always XML.
I don't know why the RestClient needs to build a HttpWebRequest like that. Any meaning to do that?
If we specified both JSon and XMl message format in a Http Request, which one works finally? Is it allowed?
Thanks. Have a good day.
RestSharp will use the correct handler based on the content type of the response. That's what those AddHandlers are doing; its configuring the RestClient to accept certain content types in the response and mapping those types to deserializers. Normally you would want to set an accept header for the json content type which notifies the server to send json in the response.
request.AddHeader("Accept", "application/json")
Of course, this assumes that the server you are hitting is configured to respond with json.
sorry i am a new comer,i just want to know how we can make HTTP Client in iPhone,like java
we make HTTPClient like
httpclient = new DefaultHttpClient();
if(Settingdb.getLocation() != null && Settingdb.getLocation().length()
httppost = new HttpPost(Settingdb.getLocation());
i need this code in iPhone (objective C )
You can make HTTP request by using URL Loading System