dポイントプレゼントキャンペーン実施中!

下記のようなコードを書いて、自分が作成しているWebアプリ(A)から、別のサービス(B)にアクセスし、結果を取得しようとしています。
AとBは同じサーバ上にあり、ドメインも同じです。

private String hoge(HttpServletRequest req, HttpServletResponse res) {

Cookie[] cookies = req.getCookies();
CookieStore cookieStore = new BasicCookieStore();
if (cookies != null) {
for (Cookie c : cookies) {
BasicClientCookie cookie = new BasicClientCookie(c.getName(),
c.getValue());
cookie.setAttribute(ClientCookie.MAX_AGE_ATTR,
Integer.toString(c.getMaxAge()));
cookie.setComment(c.getComment());
cookie.setDomain(c.getDomain());
cookie.setPath(c.getPath());
cookie.setSecure(c.getSecure());
cookie.setVersion(c.getVersion());
cookieStore.addCookie(cookie);
}
}

List<Header> headerList = new ArrayList<Header>();
headerList.add(new BasicHeader("user-agent", req.getHeader("user-agent")));

String url = "https://xxxxx.com/hogehoge/"; //Bのサービス

RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1000).setSocketTimeout(1000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig).setDefaultHeaders(headerList)
.setDefaultCookieStore(cookieStore).build();
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet, context);
int statusCode = response.getStatusLine().getStatusCode();

~省略~
} catch (IOException e) {
~省略~
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e1) {
// ignore
}
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
// ignore
}
}
}

BではAから送信されるCookieを利用して処理を行うのですが、上記のコードだとB側でCookieを取得することが出来ていません。(同じようにセットしたヘッダは送信できています)
Bへのリクエストヘッダにクライアントから取得したCookie情報を追加するには、他に必要な処理があるのでしょうか?

環境は下記の通りです。
Java:1.8
HttpClient:4.3.6

A 回答 (1件)

実験したわけではないので、思いつきになりますが、回答しておきます。



AからBにアクセスするとき、Aに送られてきたCookieをコピーしてBに送っているようですが、その時、CookieのドメインとパスもAに対するもののままコピーしています。

ドメインが同じであるなら、パスだけでも、Bに対応したものに変更する必要があると思います。

HttpClientには詳しくないので、想像になりますが、CookieStore に設定されたCookieが全部そのまま送られるわけではなく、その中から、ドメインとパスが対応するものを選んで、アクセス先に送られるのだと思います。
    • good
    • 0
この回答へのお礼

ご回答ありがとうございます。
教えて頂いたことを参考に、ドメインとパスをBのサービス用に指定したところ、
無事にBのサービス側でCookieの値を受け取ることが出来ました!
本当にありがとうございます。
とても助かりました!

お礼日時:2015/03/19 20:19

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!