投稿リクエスト後に Cookie を保存したい。httpClient 実現のためのクラス:
public class JSONParser {
CookieStore store = new BasicCookieStore();
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
private static final DefaultHttpClient httpClient = new DefaultHttpClient() ;
public static DefaultHttpClient getInstance() { return httpClient; }
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
DefaultHttpClient httpClient = JSONParser.getInstance();
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Android-AEApp,ID=2435743");
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("User-Agent","Android-AEApp,ID=2435743");
cookies = httpClient.getCookieStore().getCookies();
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Cookie", "PHPSESSID=lc89a2uu0rj6t2p219gc2cq4i2; path=/");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
cookies = httpClient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
for (Cookie a : cookies)
cookieStore.addCookie(a);
} else {
for (Cookie a : cookies) {
cookieStore.addCookie(a);
System.out.println("- " + a.getValue().toString());
}
}
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
DefaultHttpClient のシングルトーンを作成し、それをさらにリクエストで使用したいと考えています。このように作ろうとすると:
HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
私はクッキーを取得しません。localContext を含めない場合、Cookie を取得できます
if (cookies.isEmpty()) {
for (Cookie a : cookies)
cookieStore.addCookie(a);
} else {
for (Cookie a : cookies) {
cookieStore.addCookie(a);
System.out.println("- " + a.getValue().toString());
}
}
ただし、Cookie は 2 回目のリクエストでは設定されません。私は推測します-理由はlocalContextを使用していないことにあります。何が問題なのか教えてください。クッキーが変更されている場合、どうすればクッキーを設定できますか?