Java-Http
1 import java.io.BufferedReader;
2 import java.io.BufferedWriter;
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.io.OutputStreamWriter;
6 import java.net.HttpURLConnection;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9
10 /**
11 * HttpURLConnection
12 */
13 public class TestPost {
14 public static void main(String[] args) {
15 try {
16 URL url = new URL("");
17 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
18 connection.setRequestProperty("encoding", "UTF-8");
19 connection.setRequestMethod("POST");
20 connection.setDoInput(true);
21 connection.setDoOutput(true);
22 //根据连接对象创建输出流 将参数写入
23 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
24 bw.write("name=zhangsan&age=25");
25 bw.flush();
26 //创建输入流 获取响应数据
27 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
28 String str;
29 StringBuffer sb = new StringBuffer();
30 while((str = br.readLine())!=null) {
31 sb.append(str);
32 }
33 bw.close();
34 br.close();
35 } catch (MalformedURLException e) {
36 e.printStackTrace();
37 } catch (IOException e) {
38 e.printStackTrace();
39 }
40 }
41 }
1 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; /**
* URLConnection
*/
public class TestGet {
public static void main(String[] args) {
try {
URL url = new URL("https://www.baidu.com");
//打开连接
URLConnection openConnection = url.openConnection();
//获取连接中的输入流openConnection.getInputStream()返回字节流,通过转成字符流并包装一个缓冲流
BufferedReader br = new BufferedReader(
new InputStreamReader(openConnection.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while((str = br.readLine())!=null) {
sb.append(str);
}
System.out.println(sb);
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
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.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* HttpGet
*/
public class HttpClientGetTest {
public static void main(String[] args) {
HttpClient client = HttpClients.createDefault();
try {
HttpGet get = new HttpGet("http://www.baidu.com");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity,"UTF-8"); System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; 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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* HttpPost
*/
public class HttpClientPostTest {
public static void main(String[] args) {
try {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://www.baidu.com");
//参数集合
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
//添加数据
parameters.add(new BasicNameValuePair("name", "zhangsan"));
//将参数放到实体中
post.setEntity(new UrlEncodedFormEntity(parameters));
//设置请求方式
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity,"UTF-8");
//打印响应信息
System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
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.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
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;
/**
* @ClassName: HttpReqUtil
* @Description: http请求工具类
*/
public class HttpReqUtil { private static CookieStore cookieStore = new BasicCookieStore();
/**
* @Title: httpReqConfig
* @Description: 请求配置
* @param httpRequestBase
* @return void 返回类型
* @throws
*/
public static void httpReqConfig(HttpRequestBase httpRequestBase) {
// header配置
httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
httpRequestBase.setHeader("Accept", "*/*");
httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
httpRequestBase.setHeader("Accept-Encoding", "gzip, deflate"); // 请求超时设置
RequestConfig config = RequestConfig.custom() //获取Builder对象
.setConnectionRequestTimeout(20000) //设置请求超时时间
.build(); //构建RequestConfig对象 httpRequestBase.setConfig(config); //将RequestConfig添加到请求中
} /**
* @Title: sendGet
* @Description: 发送get请求
* @param url
* @param param
* @return String 返回类型
* @throws
*/
public static String sendGet(String url, String param) { // 初始化
String result = null;
CloseableHttpResponse response = null;
String finalUrl = url + "?" + param;
// 创建httpclient
CloseableHttpClient httpclient = HttpClients.custom()
//请求中cookie由cookie管理,存储第一次登陆后服务器返回的cookie,之后登陆后的请求都带上该cookie
.setDefaultCookieStore(cookieStore)
.build(); try {
// 发送get请求+header
HttpGet httpGet = new HttpGet(finalUrl); // 添加header
httpReqConfig(httpGet);
response = httpclient.execute(httpGet); // 获取响应内容
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭数据流
if(response!=null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
// 关闭连接
if(httpclient!=null) {
httpclient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
} /**
* @Title: sendPost
* @Description: 发送post请求
* @param url
* @param param
* @return String 返回类型
* @throws
*/
public static String sendPost(String url, String param) {
// 初始化
String result = null;
CloseableHttpResponse response = null;
// 创建httpclient
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
try {
HttpPost httpPost = new HttpPost(url);
// 添加header
httpReqConfig(httpPost); StringEntity stringEntity = new StringEntity(param, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded"); // 发送post请求
httpPost.setEntity(stringEntity);
response = httpclient.execute(httpPost); // 获取响应内容
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭数据流
if(response!=null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
// 关闭连接
if(httpclient!=null) {
httpclient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
} public static void main(String[] args) { // 案例:登陆接口
String url_a = "http://www.nuandao.com/public/lazyentrance";
String param_a = "isajax=1&remember=1&email=xxxxx@qq.com&password=testing1?&agreeterms=1&itype=&book=1&m=0.2757277030262314";
sendPost(url_a, param_a); // // 案例:购物车接口
// String url_b = "http://www.nuandao.com/shopping/cart";
// String param_b = "countdown=1&m=0.3810762454661424";
// sendPost(url_b, param_b); /*
* //案例 String url_c = "http://www.nuandao.com/Ajax/personal"; String
* param_c =
* "default=1&pagesign=user&url=http%3A%2F%2Fwww.nuandao.com%2Fuser%2Fmyorder&m=0.7948146575033792";
* sendPost(url_c,param_c);
*
* //案例 String url_d =
* "https://m.jiuxian.com/m_v1/goods/get_goods_num_by_province"; String
* param_d = "goods_id=28045&province_id=500"; sendPost(url_d,param_d);
*/
}
}
Java-Http的更多相关文章
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
- 故障重现(内存篇2),JAVA内存不足导致频繁回收和swap引起的性能问题
背景起因: 记起以前的另一次也是关于内存的调优分享下 有个系统平时运行非常稳定运行(没经历过大并发考验),然而在一次活动后,人数并发一上来后,系统开始卡. 我按经验开始调优,在每个关键步骤的加入如 ...
- Elasticsearch之java的基本操作一
摘要 接触ElasticSearch已经有一段了.在这期间,遇到很多问题,但在最后自己的不断探索下解决了这些问题.看到网上或多或少的都有一些介绍ElasticSearch相关知识的文档,但个人觉得 ...
- 论:开发者信仰之“天下IT是一家“(Java .NET篇)
比尔盖茨公认的IT界领军人物,打造了辉煌一时的PC时代. 2008年,史蒂夫鲍尔默接替了盖茨的工作,成为微软公司的总裁. 2013年他与微软做了最后的道别. 2013年以后,我才真正看到了微软的变化. ...
- 故障重现, JAVA进程内存不够时突然挂掉模拟
背景,服务器上的一个JAVA服务进程突然挂掉,查看产生了崩溃日志,如下: # Set larger code cache with -XX:ReservedCodeCacheSize= # This ...
- 死磕内存篇 --- JAVA进程和linux内存间的大小关系
运行个JAVA 用sleep去hold住 package org.hjb.test; public class TestOnly { public static void main(String[] ...
- 【小程序分享篇 一 】开发了个JAVA小程序, 用于清除内存卡或者U盘里的垃圾文件非常有用
有一种场景, 手机内存卡空间被用光了,但又不知道哪个文件占用了太大,一个个文件夹去找又太麻烦,所以我开发了个小程序把手机所有文件(包括路径下所有层次子文件夹下的文件)进行一个排序,这样你就可以找出哪个 ...
- Java多线程基础学习(二)
9. 线程安全/共享变量——同步 当多个线程用到同一个变量时,在修改值时存在同时修改的可能性,而此时该变量只能被赋值一次.这就会导致出现“线程安全”问题,这个被多个线程共用的变量称之为“共享变量”. ...
- Java多线程基础学习(一)
1. 创建线程 1.1 通过构造函数:public Thread(Runnable target, String name){} 或:public Thread(Runnable target ...
- c#与java的区别
经常有人问这种问题,用了些时间java之后,发现这俩玩意除了一小部分壳子长的还有能稍微凑合上,基本上没什么相似之处,可以说也就是马甲层面上的相似吧,还是比较短的马甲... 一般C#多用于业务系统的开发 ...
随机推荐
- Java [Leetcode 383]Ransom Note
题目描述: Given an arbitrary ransom note string and another string containing letters from al ...
- SSM框架——Spring+SpringMVC+Mybatis的搭建
1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One ...
- 剑指offer-第四章解决面试题的思路(顺序打印矩阵)
题目:输入一个矩阵,按照从外向里的顺序依次打印出每一个数.(画图让抽象的问题形象化) 思路:打印矩阵时,把每一层当做一个圈来打印,找到打印整个矩阵的截止条件. 从上图中我可以看到一个6*6的矩阵(长宽 ...
- Codeforces Round #318 [RussianCodeCup Thanks-Round] (Div. 1) C. Bear and Drawing
题目链接:http://codeforces.com/contest/573/problem/C题目大意:在两行无限长的点列上面画n个点以及n-1条边使得构成一棵树,并且要求边都在同一平面上且除了节点 ...
- rbenv配置
git clone https://github.com/rbenv/rbenv.git ~/.rbenv # 用来编译安装 ruby git clone git://github.com/sstep ...
- Internet上的网络层
TCP/IP协议栈第三层是网络层,网络层的目的是实现两个系统之间的数据透明传送,具体功能包括寻址和路由选择.连接和建立.保持和终止等. TCP/IP协议给internet上的每台主机和路由分配一个地址 ...
- jenkins使用HTML Publisher Plugin插件 拉取报告样式缺失问题解决
---------------------------------------------------------临时解决方案----亲测ok 要解决该问题,方式也比较简单,就是修改Content S ...
- 【转】Jmeter内存溢出处理方式记录
方法一: 使用jmeter进行压力测试时 遇到一段时间后报内存溢出outfmenmory错误,导致jmeter卡死了,先尝试在jmeter.bat中增加了JVM_ARGS="- Xmx204 ...
- monolog 应该是世界上最好的日志插件了
引入 composer require monolog/monolog 官网 https://github.com/Seldaek/monolog 创建工具类 <?php /** * Creat ...
- MFC学习(一) MFC基础类及其层次结构
从类CCmdTarget派生出绝大多数MFC中的类,其层次结构如下图: 从根类Cobject层层派生出绝大多数MFC中的类,层次结构如下图: MFC中重点类: CObject类是MFC的绝大部分类的基 ...