CloseableHttpResponse的使用

來源:互聯網
上載者:User

標籤:blog   http   io   os   ar   使用   java   for   sp   

基本邏輯是:

1、定義一個用戶端

2、定義一個方法(GET,POST等)

3,、用戶端執行這個方法並返回內容

 

/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URI;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.client.methods.RequestBuilder;import org.apache.http.cookie.Cookie;import org.apache.http.impl.client.BasicCookieStore;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;/** * A example that demonstrates how HttpClient APIs can be used to perform * form-based logon. */public class ClientFormLogin {    public static void main(String[] args) throws Exception {        BasicCookieStore cookieStore = new BasicCookieStore();        CloseableHttpClient httpclient = HttpClients.custom()                .setDefaultCookieStore(cookieStore)                .build();        try {            HttpGet httpget = new HttpGet("http://...");            CloseableHttpResponse response1 = httpclient.execute(httpget);            try {                HttpEntity entity = response1.getEntity();                System.out.println("Login form get: " + response1.getStatusLine());                System.out.println("Initial set of cookies:");                List<Cookie> cookies = cookieStore.getCookies();                if (cookies.isEmpty()) {                    System.out.println("None");                } else {                    for (int i = 0; i < cookies.size(); i++) {                        System.out.println("- " + cookies.get(i).toString());                    }                }                                //輸出網頁源碼                           String result = EntityUtils.toString(response1.getEntity(), "utf-8");                  System.out.println(result);   
                // 關閉EntityUtils
EntityUtils.consume(entity);

} finally { response1.close(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("https://someportal/")) .addParameter("IDToken1", "username") .addParameter("IDToken2", "password") .build(); CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } }private static String getStringFromInputStream(InputStream is) throws IOException {// TODO Auto-generated method stubByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len =-1;try {while((len = is.read(buffer))!= -1){baos.write(buffer,0,len);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}is.close();String html = baos.toString();baos.close();return html;}}

  

 

CloseableHttpResponse的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.