1

我正在尝试在 httpAsyncClient 库中设置 cookie,但问题是我无法找到它的示例。这是我的代码。

 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;

这是我的 ConvertToJson 方法

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;
       }
4

1 回答 1

2

首先从请求头中获取cookie:

            Future<HttpResponse> future = httpclient.execute(post, null);
            HttpResponse resp = future.get();
            header = resp.getHeaders("cookie");
            myCookies = header.toString();

获取 cookie 后将其放入 HTTPContext 并发送它,它应该可以工作。

            CookieStore cookieStore = new BasicCookieStore();
            Cookie cookie = new BasicClientCookie("cookie", myCookies);
            cookieStore.addCookie(cookie);
            httpContext = new BasicHttpContext();
            httpContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
于 2012-12-27T08:19:34.733 回答