Issue
I am trying to set cookie in httpAsyncClient library but problem is i am not figure out to find example of it..here is my code.
public JSONArray sendRequest(List<BasicNameValuePair> postPairs){
HttpAsyncClient httpclient = null;
try {
httpclient = new DefaultHttpAsyncClient();
httpclient.start();
HttpPost post = new HttpPost("http://10.0.0.62:8080/IDocWS"+postPairs.get(0).getValue());
BasicCookieStore cookie = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE,cookie);
post.setEntity(new UrlEncodedFormEntity( postPairs, HTTP.UTF_8 ) );
Future<HttpResponse> future = httpclient.execute(post, null);
HttpResponse resp = future.get();
HttpEntity entity = resp.getEntity();
JSONArray jArray = CovnertToJson(entity);
return jArray;
and here is my ConvertToJson method
public JSONArray CovnertToJson(HttpEntity entity){
try{
InputStream inputStream1= entity.getContent();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(inputStream1, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line1;
while ((line1 = reader1.readLine()) != null) {
sb.append(line1);
}
JSONArray jArray = new JSONArray(sb.toString());
return jArray;
}
Solution
First get cookie from request header:
Future<HttpResponse> future = httpclient.execute(post, null);
HttpResponse resp = future.get();
header = resp.getHeaders("cookie");
myCookies = header.toString();
After getting cookie put it in HTTPContext and send it and it shoud work.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("cookie", myCookies);
cookieStore.addCookie(cookie);
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
Answered By - jahan