HttpClient 发送post和get请求 调用第三方webservice

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/3.
 */
public class TestHTTPClient {
//    private static Log logger=LogFactory.getLog(TestHTTPClient.class);

    public static String post(String url,List<NameValuePair> nameValuePairs) throws IOException {
        CloseableHttpClient httpClient= HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(url);
        CloseableHttpResponse httpResponse=null;
        HttpEntity httpResponseEntity=null;
        UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(nameValuePairs,"utf-8");
        httpPost.setEntity(urlEncodedFormEntity);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectionRequestTimeout(5000).build();
        httpPost.setConfig(requestConfig);
        httpResponse = httpClient.execute(httpPost);
        InputStream inputStream=null;
        System.out.println(httpResponse.getStatusLine());
        if (httpResponse.getStatusLine().getStatusCode()==200){
            httpResponseEntity = httpResponse.getEntity();
//            System.out.println("响应内容:"+EntityUtils.toString(httpResponseEntity));//entity的流不可重复读,查看源码可以发现此处流已关闭
            inputStream = httpResponseEntity.getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            String line=null;
            StringBuffer stringBuffer=new StringBuffer();
            while ((line=bufferedReader.readLine())!=null){
                stringBuffer.append(line);
            }
            System.out.println("----------"+stringBuffer.toString()+"---------");
            return String.valueOf(stringBuffer);
        }else{
            System.out.println("请求出错!");
        }
        httpResponse.close();
        httpClient.close();
        inputStream.close();
        return null;
    }

    public static String get(String url) throws IOException {
        CloseableHttpClient httpClient=HttpClients.createDefault();
        HttpGet httpGet=new HttpGet(url);
        CloseableHttpResponse httpResponse=null;
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectionRequestTimeout(2000).build();
        httpGet.setConfig(requestConfig);
        httpResponse=httpClient.execute(httpGet);
        InputStream inputStream=null;
        System.out.println(+httpResponse.getStatusLine().getStatusCode());
        if (httpResponse.getStatusLine().getStatusCode()==200){
            HttpEntity httpResponseEntity = httpResponse.getEntity();
//            System.out.println("响应内容:"+EntityUtils.toString(httpResponseEntity));//entity的流不可重复读,查看源码可以发现此处流已关闭
            inputStream = httpResponseEntity.getContent();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            String line=null;
            StringBuffer stringBuffer=new StringBuffer();
            while ((line=bufferedReader.readLine())!=null){
                stringBuffer.append(line);
            }
            System.out.println("----------"+stringBuffer.toString()+"---------");
            return String.valueOf(stringBuffer);
        }else{
            System.out.println("请求出错!");
        }
        return null;

    }

    public static void main(String[] args) {

//        testHTTPClient.sendGetRequest();
//        testHTTPClient.sendPostRequest();
//        get("http://www.baidu.com");
        List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mobileCode","15665383398"));
        nameValuePairs.add(new BasicNameValuePair("userID",""));
        try {
            String msg = post("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo", nameValuePairs);
            Document document = DocumentHelper.parseText(msg);
            Element root = document.getRootElement();
            System.out.println(root.getText());
            if (root.getText()!=null&&!"".equals(root.getText())){
                String[] split = root.getText().split(":");
                System.out.println(split[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private static CloseableHttpClient getHttpClient(){
        CloseableHttpClient httpClient=HttpClients.createDefault();
        return httpClient;
    }

    private static void closeHttpClient(CloseableHttpClient httpClient) {
        if (httpClient!=null){
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

在练习的时候遇到httpclent:java.io.IOException: Attempted read from closed stream.这个问题的原因httpEntity的流不可重复读,查看源码可以发现此处流已关闭

部分源码如下:

public static String toString(HttpEntity entity, Charset defaultCharset) throws IOException, ParseException {
    Args.notNull(entity, "Entity");
    InputStream instream = entity.getContent();
    if(instream == null) {
        return null;
    } else {
        try {
            Args.check(entity.getContentLength() <= 2147483647L, "HTTP entity too large to be buffered in memory");
            int i = (int)entity.getContentLength();
            if(i < 0) {
                i = 4096;
            }

            Charset charset = null;

            try {
                ContentType reader = ContentType.get(entity);
                if(reader != null) {
                    charset = reader.getCharset();
                }
            } catch (UnsupportedCharsetException var13) {
                throw new UnsupportedEncodingException(var13.getMessage());
            }

            if(charset == null) {
                charset = defaultCharset;
            }

            if(charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }

            InputStreamReader reader1 = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);
            char[] tmp = new char[1024];

            int l;
            while((l = reader1.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }

            String var9 = buffer.toString();
            return var9;
        } finally {
            instream.close();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值