java 中http通信_Java中的HTTP通信2-实战篇

如今成熟的应用必然离不开读写网络数据,而 HTTP 请求正式最普遍且常用的网络通信协议,所以掌握使用 Get 和 Post 方式进行 HTTP 通信十分必要。

核心内容:

使用 HTTP 的 Get 方式与 Post 方式进行网络通信。

使用 HttpClient 简化 HTTP 通讯操作。

一、使用 Http 的 Get 方式读取网络数据

简介:介绍使用Get方式与网络通信是最常见的 Http通信, 建立链接之后就可以通过输入流读取网络数据。

案例1: HTTP GET请求DEMO

package com.netease.hettpdemo;

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;

/**

* HTTP GET请求DEMO

*/

public class HTTPGetDemo {

public static void main(String[] args) {

new ReadByGet().start();

}

}

class ReadByGet extends Thread{

private static final String TEST_GET_URL="http://fanyi.youdao.com/openapi.do?wecome=";

@Override

public void run() {

try {

// 实例化URL对象

URL url=new URL(TEST_GET_URL);

// 建立并获取HTTP连接

URLConnection connection= url.openConnection();

// 获取输入流对象

InputStream is=connection.getInputStream();

// 指定解析输入流的编码格式

InputStreamReader isr=new InputStreamReader(is,"UTF-8");

// 缓存读取器

BufferedReader br=new BufferedReader(isr);

String line;

StringBuilder builder=new StringBuilder();

while ((line=br.readLine())!=null) {

builder.append(line);

}

System.out.println(builder.toString());

// 关闭各种流对象

br.close();

isr.close();

is.close();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

二、使用 Http 的 Post 方式与网络交互通信

简介:Post 方式需要向网络传输一部分数据,所以同时具有输入流和输出流。本课时讲解使用 Http 的 Post 方式与网络交互通信。

案例2:HTTP POST请求DEMO

package com.netease.hettpdemo;

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 HTTPPostDemo {

public static void main(String[] args) {

ReadByPost myThread=new ReadByPost();

myThread.start();

}

}

class ReadByPost extends Thread{

@Override

public void run() {

try {

// 实例化URL对象

URL url=new URL("http://fanyi.youdao.com/openapi.do");

HttpURLConnection connection=(HttpURLConnection)url.openConnection();

connection.setRequestProperty("encoding", "UTF-8");

// 设置允许该连接从网络中获取数据

connection.setDoInput(true);

// 设置允许该连接向网络传输数据

connection.setDoOutput(true);

// 设置请求方法

connetion.setRequestMethod("POST");

// 设置请求体

OutputStream os=connection.getOutputStream();

OutputStreamWriter isw=new OutputStreamWriter(os, "UTF-8");

BufferedWriter bw=new BufferedWriter(isw);

bw.write("keyform=testHttpGet&key=850021564&type=data&doctype=xml&version=1.1&q=good");

bw.flush();

// 处理返回结果

InputStream is=connection.getInputStream();

InputStreamReader isr=new InputStreamReader(is,"UTF-8");

BufferedReader br=new BufferedReader(isr);

// 输出响应结果

String line;

while((line=br.readline())!=null){

System.out.println(line);

}

// 释放资源

is.close();

isr.close();

br.close();

os.close();

isw.close();

bw.close();

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

三、使用HttpClient进行Get方式通信

maven导包:

org.apache.httpcomponents

httpclient

4.5.2

案例3:HttpClient GET请求DEMO

public static final PoolingHttpClientConnectionManager CONN_MANAGER = new PoolingHttpClientConnectionManager();

public static final CloseableHttpClient HTTP_CLIENT;

public static final RequestConfig DEFAULT_REQUEST_CONFIG;

static {

CONN_MANAGER.setMaxTotal(200); // 整个连接管理器的最大连接数设

CONN_MANAGER.setDefaultMaxPerRoute(25); // 每个目标主机的最大连接数

HTTP_CLIENT = HttpClients.custom().setConnectionManager(CONN_MANAGER).build();

DEFAULT_REQUEST_CONFIG = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000).build();//设置请求和传输超时时间

}

/**

* HTTP Get请求

* @param url 请求的URL地址

* @param timeout 超时时间

* @return

*/

public static String sendGet(String url, int timeout) {

HttpGet httpget = new HttpGet(url);

if (timeout > 0) {

httpget.setConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());

} else {

httpget.setConfig(DEFAULT_REQUEST_CONFIG);

}

HttpEntity entity = null;

CloseableHttpResponse httpResponse=null;

try {

httpResponse = HTTP_CLIENT.execute(httpget);

entity = httpResponse.getEntity();

String content = EntityUtils.toString(entity, Charset.forName("UTF-8"));

return content;

} catch (Exception e) {

throw new RuntimeException("failed to get!", e);

} finally {

if (entity != null) {

try {

EntityUtils.consume(entity);

} catch (IOException e) {

LOG.error(e);

}

}

if(httpResponse!=null){

try {

httpResponse.close();

} catch (IOException e) {

LOG.error(e);

}

}

}

}

四、使用 HttpClient 进行 Post 方式通信

maven导包:

org.apache.httpcomponents

httpclient

4.5.2

案例4:HttpClient POST请求DEMO

public static final PoolingHttpClientConnectionManager CONN_MANAGER = new PoolingHttpClientConnectionManager();

public static final CloseableHttpClient HTTP_CLIENT;

public static final RequestConfig DEFAULT_REQUEST_CONFIG;

static {

CONN_MANAGER.setMaxTotal(200); // 整个连接管理器的最大连接数设

CONN_MANAGER.setDefaultMaxPerRoute(25); // 每个目标主机的最大连接数

HTTP_CLIENT = HttpClients.custom().setConnectionManager(CONN_MANAGER).build();

DEFAULT_REQUEST_CONFIG = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000).build();//设置请求和传输超时时间

}

/**

* 指定header的HTTP POST请求

* @param url 请求的URL地址

* @param params body参数

* @param headMap header参数

* @param timeout 超时时间

* @return

*/

public static String sendPost(String url, Map params, Map headMap, int timeout) {

HttpPost httpPost = new HttpPost(url);

httpPost.setConfig(DEFAULT_REQUEST_CONFIG);

List nvps = new ArrayList();

if (params != null) {

for (Entry e : params.entrySet()) {

nvps.add(new BasicNameValuePair(e.getKey(), e.getValue()));

}

}

httpPost.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8")));

if (headMap != null) {

for(Map.Entry head : headMap.entrySet()) {

httpPost.addHeader(head.getKey(), head.getValue());

}

}

HttpEntity entity = null;

CloseableHttpResponse httpResponse = null;

try {

httpResponse = HTTP_CLIENT.execute(httpPost);

entity = httpResponse.getEntity();

String content = EntityUtils.toString(entity, Charset.forName("UTF-8"));

return content;

} catch (Exception e) {

throw new RuntimeException("failed to post!", e);

} finally {

if (entity != null) {

try {

EntityUtils.consume(entity);

} catch (IOException e) {

LOG.error(e);

}

}

if(httpResponse!=null){

try {

httpResponse.close();

} catch (IOException e) {

LOG.error(e);

}

}

}

}

五、参考链接:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值