HttpComponent 实现 get提交

package com.mmt.httpClient_GET;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientGet {

    
    
    
    public static void main(String args[]){
        String urlPath = "http://www.besti.edu.cn";
        Map<Object,Object> parmas = new HashMap<Object,Object>();
        String encodeType = "utf-8";
        String resultString = getWEBPageContent(urlPath,parmas,encodeType);
        System.out.println(resultString);
        
    }
    
    public static String getWEBPageContent(String urlPath,Map<Object,Object>params,String encodeType){
        String resultString = getWEBPageString(urlPath) ;
        return resultString ;
    }

    private static String getWEBPageString(String urlPath){
        String resultString = null ;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(urlPath);
        
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            resultString = EntityUtils.toString(httpEntity);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return resultString ;
        
    }
    
    private static String streamToString(InputStream inputStream,String encodeType){
        String resultString = null ;
        
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len = 0;
        byte data[]=new byte[1024];
        try {
            while((len=inputStream.read(data))!=-1){
                byteArrayOutputStream.write(data,0,len);
            }
            byte[]allData = byteArrayOutputStream.toByteArray();
            resultString = new String(allData,encodeType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        return resultString ;
    }
    
}
View Code

 

posted @ 2018-12-01 23:59  梦想战士  阅读(46)  评论(0编辑  收藏  举报