HttpClient的应用

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class HttpClientTest {

@Test
public void jUnitTest() {
    get();
}

/**
 * HttpClient连接SSL
 */
public void ssl() {
    CloseableHttpClient httpclient = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
        try {
            // 加载keyStore d:\\tomcat.keystore
            trustStore.load(instream, "123456".toCharArray());
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }
        // 相信自己的CA和所有自签名的证书
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // 只允许使用TLSv1协议
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        // 创建http请求(get方式)
        HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
        System.out.println("executing request" + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                System.out.println(EntityUtils.toString(entity));
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * post方式提交表单(模拟用户登录请求)
 */
public void postForm() {
    // 创建默认的httpClient实例.
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // 创建httppost
    HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
    // 创建参数队列
    List<namevaluepair> formparams = new ArrayList<namevaluepair>();
    formparams.add(new BasicNameValuePair("username", "admin"));
    formparams.add(new BasicNameValuePair("password", "123456"));
    UrlEncodedFormEntity uefEntity;
    try {
        uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(uefEntity);
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("--------------------------------------");
                System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                System.out.println("--------------------------------------");
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭连接,释放资源
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
 */
public void post() {
    // 创建默认的httpClient实例.
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // 创建httppost
    HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
    // 创建参数队列
    List<namevaluepair> formparams = new ArrayList<namevaluepair>();
    formparams.add(new BasicNameValuePair("type", "house"));
    UrlEncodedFormEntity uefEntity;
    try {
        uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(uefEntity);
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("--------------------------------------");
                System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                System.out.println("--------------------------------------");
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭连接,释放资源
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 发送 get请求
 */
public void get() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        // 创建httpget.
        HttpGet httpget = new HttpGet("http://www.baidu.com/");
        System.out.println("executing request " + httpget.getURI());
        // 执行get请求.
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            System.out.println("--------------------------------------");
            // 打印响应状态
            System.out.println(response.getStatusLine());
            if (entity != null) {
                // 打印响应内容长度
                System.out.println("Response content length: " + entity.getContentLength());
                // 打印响应内容
                System.out.println("Response content: " + EntityUtils.toString(entity));
            }
            System.out.println("------------------------------------");
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭连接,释放资源
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 上传文件
 */
public void upload() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

        FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

时间: 2024-10-12 04:24:06

HttpClient的应用的相关文章

用gson和httpclient调用微信公众平台API

吐槽:微信api很无语,部分用xml,部分用json. 最近在找如何调用微信公众平台关于json相关的api比较方便,最后发现httpcliect和gson不错.如果你有更好的方式,请告诉我. 以下代码先了解如何使用gson和httpclient,有功夫再整到我的sophia里 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.

HttpClient使用详解 (一)

Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性.因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入. 一.简介 HttpClient是Apache Jakarta Common下的子项目,用

SpringMVC template和HttpClient post提交

服务器的接口如果是springmvc客户端除了用springmvc提供的RestTemplate请求如下 public class RestClient { private static Logger logger = Logger.getLogger(RestClient.class); @SuppressWarnings({ rawtypes, unchecked }) public static Object post(String url, Map<string, object="

Httpclient处理摘要认证

虽然摘要认证的安全性比BASIC认证提高了不少,但是从接口调用上来看,并不比BASIC认证复杂,而且Realm和Scheme参数都可以为空,这时候就和BASIC认证的调用方式一模一样了. import java.net.URI; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.Credentia

【黑马Android】(06)使用HttpClient方式请求网络/网易新闻案例

使用HttpClient方式请求网络 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"

使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)

这两天看了点网络编程,根据教程写了一个小的注册服务,贴出来. 本实例分别演示用GET方式和POST方式想服务器发送注册信息,分为客户端和服务器端两部分: 客户端注册用户信息,发送到服务器 服务器端接收信息并向客户端返回注册信息.(服务器端使用J2EE中的Servlet技术来实现,并发布到Tomcat服务器上) 代码运行效果如下: 客户端: 1.点击get注册按钮后: 客户端: 服务器端: 2.点击post注册按钮后: 客户端: 服务器端: 3.当服务器端关闭时: 客户端注册信息时会提示链接超时:

HttpClient(四)-- 使用代理IP 和 超时设置

1.代理IP的用处: 在爬取网页的时候,有的目标站点有反爬虫机制,对于频繁访问站点以及规则性访问站点的行为,会采集屏蔽IP措施.这时候,就可以使用代理IP,屏蔽一个就换一个IP. 2.代理IP分类: 代理IP的话 也分几种: 透明代理.匿名代理.混淆代理.高匿代理,一般使用高匿代理. 3.使用 RequestConfig.custom().setProxy(proxy).build() 来设置代理IP: public static void main(String[] args) throws

httpClient返回的数据类型,怎么弄

package com.etaoxue.api.third; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Cert

爬虫概念与编程学习之如何爬取视频网站页面(用HttpClient)(二)

先看,前一期博客,理清好思路. 爬虫概念与编程学习之如何爬取网页源代码(一) 不多说,直接上代码. 编写代码 运行 <!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=Edge" /><meta http-equiv="Content-Type" content="text/html; c

Angular 4+ HttpClient

这篇,算是上一篇Angular 4+ Http的后续: Angular 4.3.0-rc.0 版本已经发布??.在这个版本中,我们等到了一个令人兴奋的新功能 - HTTPClient API 的改进版本: HttpClient 是已有 Angular HTTP API 的演进,它在一个单独的 @angular/common/http 包中.这是为了确保现有的代码库可以缓慢迁移到新的 API: 大多数前端应用都需要通过 HTTP 协议与后端服务器通讯.现代浏览器支持使用两种不同的 API 发起 H