java在保持cookie的同时发送GET / POST请求

时间:2013-07-25 21:19:29

标签: java

我正在使用Apache HttpClient 4.2.5,我正在尝试发送GET / POST请求,同时将cookie从一个请求传递到另一个请求(就像真正的浏览器一样)。

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(get_url);

request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.setHeader("Accept-Language", "en-US,en;q=0.5");
request.setHeader("Connection", "keep-alive");

try {
     HttpResponse response = client.execute(request);
     // Get cookies & pass them to a POST request
} catch (IOException e) {
     System.out.println("Error: " + e.getMessage());
}

有什么类似PHP的cURL功能吗? cURL简单明了,但很难在Google上找到能够满足我所需要的Java代码。

我想要的很简单。让我发送POST和GET请求。同时,传递cookie并让我设置自己的标题。在Java中有类似的东西吗?

2 个答案:

答案 0 :(得分:4)

HttpClient automatically handles cookies只要您使用相同的DefaultHttpClient对象。

答案 1 :(得分:2)

  

有什么类似PHP的cURL功能吗? cURL简单明了但是很难在Google上找到能够满足Java需求的代码

来自Curl世界的东西:

curl -b -L -i  -X POST   
-d 'id=105'  
-d 'json={"orderBy":0,"categoryRelevant":false'}  \ http://env-findwifi.wifi.com/lClient/

**评论:

-b :: enable cookies (by default its disabled)
-L :: activate redirect
-i :: show output

但是,如果你真的想玩Java,那么就是代码片段:

List<Cookie> mCookies = null;

...

public void redirect(String url){

    StringBuilder buff = new StringBuilder();

    DefaultHttpClient httpclient = null;
    //      boolean success = false;

    try {           
        Log.d("test_runner","send Data started");


        HttpParams params = new BasicHttpParams();
        int m_timeout = 60000;
        ConnManagerParams.setTimeout(params, m_timeout);            
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpConnectionParams.setConnectionTimeout(params, m_timeout);    // connection timeout
        HttpConnectionParams.setSoTimeout(params, m_timeout);            // socket timeout

        HttpClientParams.setRedirecting(params, false);


        httpclient = new DefaultHttpClient(params);


        Log.d("test_runner", "URL: " + url);

        HttpGet httpget = new HttpGet(url);




        HttpContext context = new BasicHttpContext(); 
        HttpResponse response = httpclient.execute(httpget, context);



        //HttpResponse response = httpclient.execute(httpget);

        mCookies = httpclient.getCookieStore().getCookies();

        if (mCookies.isEmpty()) {
            Log.d("test_runner", "Cookies: None");
        } else {
            for (int i = 0; i < mCookies.size(); i++) {
                System.out.println("- " + mCookies.get(i).toString());
                Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString());
            }
        }

        int statusCode =  response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Location");

            if (headers != null && headers.length != 0) {
                String newUrl =  headers[headers.length - 1].getValue();

                redirect(newUrl);                   

            } 
        }   
        else{ // status 200

            HttpHost currentHost = (HttpHost)  context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            mHost = currentHost.toURI();

            HttpEntity entity = response.getEntity();

            if (entity != null) {


                InputStream is = entity.getContent();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr, 1024 * 4);
                String line = null;
                while ( (line = br.readLine()) != null) {
                    //System.out.println("Data Sender: " +  line);

                    buff.append(line).append("\n");

                }
                is.close();

            } else {
                Log.d("test_runner", "Data Sender: response is null");
            }

            Log.d("test_runner", "Output: " +  buff);

            // do something


        }
    } catch (Exception e) {
        Log.e("test_runner", ThrowableToString.fromThrowableToString(e));
    }

    if (httpclient != null) {           
        httpclient.getConnectionManager().shutdown();
    }       

}

您可以使用cookies进行发布:

    private void doPost(String formAction, String inputRootValue,
        String inputRootName, String onSubmitName, String onSubmitVal) {

    StringBuilder buff = new StringBuilder();

    DefaultHttpClient httpclient = null;

    try {  

    HttpParams params = new BasicHttpParams();
    int m_timeout = 60000;
    ConnManagerParams.setTimeout(params, m_timeout);            
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);



    HttpClientParams.setRedirecting(params, false);


     CookieStore cookieStore = new BasicCookieStore(); 



     for(Cookie cook : mCookies){
         cookieStore.addCookie(cook); 
     }

     httpclient = new DefaultHttpClient(params);
     httpclient.setCookieStore(cookieStore);

     if(mHost != null){
         formAction =  mHost + "/www/" + formAction; 
     }
     else{
         formAction =  "http://localhost/www/" + formAction; 
     }




    HttpPost httpost = new HttpPost(formAction);

    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair(inputRootName, inputRootValue));
    nvps.add(new BasicNameValuePair(onSubmitName, onSubmitVal));


    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));




    HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    if (entity != null) {

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if(statusCode != 200){

        }

        Log.d("test_runner", "response.getStatusLine: " + response.getStatusLine());

        InputStream is = entity.getContent();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ( (line = br.readLine()) != null) {
            //System.out.println("Data Sender: " +  line);

            buff.append(line).append("\n");


        }
        is.close();

        //entity.consumeContent();
    } else {

    }

    Log.d("test_runner", "response: " + buff.toString());



} catch (Exception e) {
    Log.e("test_runner", ThrowableToString.fromThrowableToString(e));
}

if (httpclient != null) {
    // resource cleanup
    httpclient.getConnectionManager().shutdown();
}


}