java实现http client_java实现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 formparams = new ArrayList();

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 formparams = new ArrayList();

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();

}

}

}

}

【commons-httpclient】Java中HttpClient工具访问Web请求

注意jar包是: HttpClient工具使用 HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程 ...

java实现利用httpclient访问接口

HTTP协议时Internet上使用的很多也很重要的一个协议,越来越多的java应用程序需要通过HTTP协议来访问网络资源. HTTPClient提供的主要功能: 1.实现了所有HTTP的方法(GET ...

Java通过httpclient获取cookie模拟登录

package Step1; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Htt ...

cxf整合spring发布rest服务 httpclient访问服务

1.创建maven web项目并添加依赖 pom.xml 3.0

使用HttpClient访问接口(Rest接口和普通接口)

这里总结一下使用HttpClient访问外部接口的用法.后期如果发现有什么缺陷会更改.欢迎读者指出此方法的不足之处. 首先,创建一个返回实体: public class HttpResult { // ...

Java成员的访问权限控制

Java中的访问权限控制包含两个部分: 类的访问权限控制 类成员的访问权限控制 对类来说,访问权限控制修饰符可以是public或者无修饰符(默认的包访问权限): 对于类成员来说,访问权限控制修饰符可以 ...

浅析Java中的访问权限控制

浅析Java中的访问权限控制 今天我们来一起了解一下Java语言中的访问权限控制.在讨论访问权限控制之前,先来讨论一下为何需要访问权限控制.考虑两个场景: 场景1:工程师A编写了一个类ClassA,但 ...

java类的访问权限

1.解析 Java有四种访问权限, 其中三种有访问权限修饰符,分别为private,public和protected,还有一种不带任何修饰符. private: Java语言中对访问权限限制的最窄的修 ...

在java程序中访问windows有用户名和密码保护的共享目录

在java程序中访问windows有用户名和密码保护的共享目录 Posted on 2015-11-20 14:03 云自无心水自闲 阅读(3744) 评论(0)  编辑  收藏 --> Jav ...

随机推荐

iOS--UILable自适应大小

#import "ViewController.h" @interface ViewController () @property(strong,nonatomic) UILabe ...

【MongoDB】MongoDB 3.2 SCRAM-SHA-1验证方式

新版本已取消addUser方法,改使用createUser方法 官方地址:https://docs.mongodb.com/manual/tutorial/create-users/ 官方地址:htt ...

JavaEE7 HTML5利用WebSocket实现即时通讯

HTML5给Web浏览器带来了全双工TCP连接websocket标准服务器的能力. 换句话说,浏览器能够与服务器建立连接,通过已建立的通信信道来发送和接收数据而不需要由HTTP协议引入额外其他的开销来 ...

Java自学手记——struts2

struts2框架 struts2是一种基于MVC模式的框架,是在struts1的基础上融合了xwork的功能. struts2框架预处理了一些功能: >请求数据自动封装, >文件上传的功 ...

使用springcloud zuul构建接口网关

一  微服务网关背景及简介 不同的微服务一般有不同的网络地址,而外部的客户端可能需要调用多个服务的接口才能完成一个业务需求.比如一个电影购票的收集APP,可能回调用电影分类微服务,用户微服务,支付微服 ...

[Swift]LeetCode356. 直线对称 $ Line Reflection

Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given ...

Random Maze HDU - 4067(预定义状态建边(贪心建边))

Random Maze Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

java大数相加

import java.math.BigInteger; import java.util.Scanner; public class Bignum{    public static void ma ...

Asp.Net IIS7.5伪静态设置

注意:先要将应用池设置为集成模式,修改OK后,再改成经典模式.否则,什么托管程序出不来. 1.新建网站,这里不做介绍,很简单.并把网站设置为集成模式 2.添加通配符脚本映射 打开之后显示如下界面,在右 ...

外业数据采集平台(GPS+Android Studio+Arcgis for android 100.2.1)

外业数据采集平台 1. 综述 在室外,通过平板或者手机接收GPS坐标,实时绘制点.线.面数据,以便为后续进行海域监测.土地确权.地图绘图提供有效数据和依据. 2. 技术路线 Android studi ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值