Http(get,post)及HttpClient(get,post)的简单使用
1. 使用 Http 的 Get 方式读取网络数据
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; public class TestHttpGet { public static void main(String[] args) {
new ReadByGet().start();
}
static class ReadByGet extends Thread{
@Override
public void run() {
try {
URL url = new URL("http://fanyi.youdao.com/openapi.do?keyfrom=jkxyuvi&key=1530995034&type=data&doctype=xml&version=1.1&q=welcom");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); String line;
StringBuilder builder = new StringBuilder(); while((line = br.readLine())!=null){
builder.append(line); }
br.close();
isr.close();
is.close(); System.out.println(builder.toString()); } catch (MalformedURLException e) { e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
2. 使用 Http 的 Post 方式与网络交互通信
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; public class TestHttpPost { public static void main(String[] args) {
new ReadByPost().start();
} }
class ReadByPost extends Thread{
@Override
public void run() {
try {
URL url = new URL("http://fanyi.youdao.com/openapi.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("encoding", "UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST"); OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw); bw.write("keyfrom=jkxyuvi&key=1530995034&type=data&doctype=xml&version=1.1&q=welcome");
bw.flush();//强制输出 InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while((line = br.readLine())!=null){
builder.append(line);
} bw.close();
osw.close();
os.close();
br.close();
isr.close();
is.close();
System.out.println(builder.toString()); } catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3. 使用HttpClient进行Get方式通信
先下载HttpClient相关依赖包,地址: http://hc.apache.org/downloads.cgi
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; public class TestHttpClientGet { public static void main(String[] args) {
new Get().start();
} }
class Get extends Thread{ HttpClient client = HttpClients.createDefault(); @Override
public void run() { HttpGet get = new HttpGet("http://www.bai.com");
try {
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();
} }
}
4. 使用 HttpClient 进行 Post 方式通信
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; public class TestHttpClientPost { public static void main(String[] args) {
new Post().start();
} }
class Post extends Thread{ HttpClient client = HttpClients.createDefault(); @Override
public void run() {
HttpPost post = new HttpPost("http://fanyi.youdao.com/openapi.do"); try {
List<BasicNameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("keyfrom", "jkxyuvi"));
parameters.add(new BasicNameValuePair("key", ""));
parameters.add(new BasicNameValuePair("type", "data"));
parameters.add(new BasicNameValuePair("doctype", "xml"));
parameters.add(new BasicNameValuePair("version", "1.1"));
parameters.add(new BasicNameValuePair("q", "welcome"));
post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8")); 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();
} }
}
与java自带的http通信,HttpClient用起来确实方便的多。
Http(get,post)及HttpClient(get,post)的简单使用的更多相关文章
- 【Cocos2d-x】 HttpClient 网络通信(Http)的简单应用
Cocos2dx 为我们封装了在cocos2dx中http的网络框架,其文件在cocos2dx引擎包的extensions\network文件下的 HttpClient.HttpRequest .Ht ...
- HttpClient(4.3.5) - 简单示例
HttpClient 是一个客户端的 HTTP 传输库,而不是浏览器.HttpClient 的目的是传输和接收 HTTP 报文.HttpClient 不会尝试去处理报文内容,执行嵌入 HTML 内的 ...
- HttpClient抓取网页内容简单介绍
版本HttpClient3.1 1.GET方式 第一步.创建一个客户端,类似于你用浏览器打开一个网页 HttpClient httpClient = new HttpClient(); 第二步.创建一 ...
- 利用HttpClient写的一个简单页面获取
之前就听说过利用网络爬虫来获取页面,感觉还挺有意思的,要是能进行一下偏好搜索岂不是可以满足一下窥探欲. 后来从一本书上看到用HttpClient来爬取页面,虽然也有源码,但是也没说用的HttpClie ...
- HttpClient&Jsoup爬虫的简单应用
详细的介绍已经有很多前辈总结,引用一下该篇文章:https://blog.csdn.net/zhuwukai/article/details/78644484 下面是一个代码的示例: package ...
- HttpClient 之Fluent API 简单使用
相比于HttpClient 之前的版本,HttpClient 4.2 提供了一组基于流接口(fluent interface)概念的更易使用的API,即Fluent API. 为了方便使用,Fluen ...
- Windows Phone 十六、HttpClient
HttpClient 对象也可以实现网络请求 相对于 HttpWebRequest 对象来说,HttpClient 操作更简单,功能更强大 HttpClient 提供一系列比较简单的API来实现基本的 ...
- HttpClient通过GET和POST获取网页内容
中国银行支付网关---银行回调的接口 最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面 /** * 中国银行支付网关---银行回调的接口 * @svncode svn://10. ...
- HttpURLConnection&HttpClient网络通信
一:HttpURLConnection简介: 用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度,这个类可以用于发送和接收流数据,其长度事先不知道. 使用这个类遵循一下模式: 获得一 ...
- 学习HttpClient,从两个小例子开始
前言 HTTP(Hyper-Text Transfer Protocol,超文本传输协议)在如今的互联网也许是最重要的协议,我们每天做的很多事情都与之有关,比如,网上购物.刷博客.看新闻等.偶尔你的上 ...
随机推荐
- SWFLoader交互
主应用程序: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx=& ...
- UVA 10651 Pebble Solitaire(bfs + 哈希判重(记忆化搜索?))
Problem A Pebble Solitaire Input: standard input Output: standard output Time Limit: 1 second Pebble ...
- [Protractor] Getting Started With Protractor
Protractor is an end-to-end testing library for AngularJS. Install: npm install -g protractor This w ...
- Python3.2官方文档翻译--继承
6.5 继承 当然,一门语言特性假设不支持继承那么名称类就失去了价值.子类继承父类的方法例如以下: class DerivedClassName(BaseClassName): <stateme ...
- java基础之导出(Excel)
function exportExcel() { $.messager .confirm( '提示信息', '您确定要导出到Excel?', function(r) { if (r) { var co ...
- java下io文件切割合并功能
package cn.stat.p1.file; import java.io.File; import java.io.FileInputStream; import java.io.FileNot ...
- O、Ω、Θ表示
转载,原网址为:http://book.2cto.com/201211/8127.html 对于任何数学函数,这三个记号可以用来度量其“渐近表现”,即当趋于无穷大时的阶的情况,这是算法分析中非常重要的 ...
- 动态代理写connection连接池Demo
public class JdbcUtil2 { //声明连接池<放到LinkedList中,操作其中对象的速度快 只需要改变连接> private static LinkedList&l ...
- HTML5 Canvas基础知识
HTML5画布 1.创建一个画布 <canvas id="myCanvas" width="200" height="100&q ...
- 比如在vi中按ctrl+z
比如在vi中按ctrl+z有个命令可以恢复会话,我忘了,大家谁记得? 分享到: 对我有用[0] 丢个板砖[0] 引用 | 举报| 编辑 删除 管理 回复次数:8 hellwolf hellwo ...