URLConnection 和 HttpClients 发送请求范例
笔记,未完全标准.
java.net.URLConnection
package test; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection; public class Test { public static void main(String[] args) throws Exception{
try {
//String info=HttpTool.sendRequestData("searchArg=宝马740", "http://localhost:8080/vhl/VhlSearch.act", new Long(300000));
String info=invoke("vhlName=大众","http://localhost:8080/vhl/vhlSearch.html");
System.out.println("接收到的车辆信息:"+info);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private static String invoke(String param, String url) throws Exception { PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("vhlsinfo", "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> <PACKET><TOTAL>哈哈</TOTAL> <VHL_LIST /></PACKET>");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));//请求编码设置
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));//返回编码设置
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} }
.
org.apache.http.impl.client.HttpClients
package com.testdemo.validate.tool; 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.ResponseHandler;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; public class ESB { public static String invoke(String paramStr,String url,String systemName) throws Exception{
CloseableHttpClient httpclient = null;
String response = null;
httpclient = HttpClients.custom().build();
HttpPost httppost = new HttpPost(url);
HttpEntity reqEntity = EntityBuilder.create()
.setContentType(ContentType.APPLICATION_JSON)
.setContentEncoding("UTF-8")
.setText(paramStr)
.build(); httppost.setEntity(reqEntity);
httppost.setHeader("userName", systemName);//在head中设置属性,后台服务端提取系统名 try {
response = httpclient.execute(httppost,
new ResponseHandler<String>() {
// 处理响应
@Override
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
String responseJson = null;
HttpEntity entity = null;
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
entity = response.getEntity();
if (entity != null) {
String sentity = EntityUtils.toString(entity, "UTF-8");
if (sentity == null|| sentity.trim().length() == 0)
return null;
responseJson = sentity;
//write(responseJson);
} else {
responseJson = response.getStatusLine().getReasonPhrase()+ " 返回的结果为空!";
}
} else {
responseJson = response.getStatusLine().toString();
}
//System.out.println(responseJson);
return responseJson;
}
}); } catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
// 5. 释放连接
httppost.releaseConnection();
httpclient.close();
}
return response;
} public static void main(String[] args) throws Exception{
String systemName = "echannel";
System.out.print(invoke("VHL_NAME=马自达&RET_TYPE=json","http://192.168.1.2:8012/vhl/vhlSearch.do",null));
// System.out.print(invoke("VHL_NAME=马自达&RET_TYPE=json","http://localhost:8080/vhl/vhlSearch.do",systemName)); } }
URLConnection 和 HttpClients 发送请求范例的更多相关文章
- URLConnection 和 HttpClients 发送请求范例【原】
笔记,未完全标准. java.net.URLConnection package test; import java.io.BufferedReader; import java.io.IOExcep ...
- 使用HttpClient发送请求、接收响应
使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象. CloseableHttpClient httpclient = HttpClients.c ...
- spring MVC 管理HttpClient---实现在java中直接向Controller发送请求
在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实 ...
- ajax发送请求跨域 - uri java代理
问题:ajax发送请求出现cors跨域 解决办法:可以通过java代理的方式,后台发送请求 1.get请求 public void proxyGet(String url) { try { URL r ...
- java后台发送请求并获取返回值
项目中需要前端发送请求给后端,而后端需要从另一个平台中取数据然后再透传给前端,通过下述代码将其实现.在此记录一下. package com.autotest.utils; import java.io ...
- java后端发送请求
package com.ty.mapapisystem.util; import java.io.BufferedReader;import java.io.FileInputStream;impor ...
- 使用HttpClient配置代理服务器模拟浏览器发送请求调用接口测试
在调用公司的某个接口时,直接通过浏览器配置代理服务器可以请求到如下数据: 请求url地址:http://wwwnei.xuebusi.com/rd-interface/getsales.jsp?cid ...
- java后台向路径发送请求获得相应参数
从java后台向一路径发送请求,获得响应的参数,put get post ,还有一个返回URL的工具类,方便代码灵活修改 import java.io.BufferedReader; import j ...
- 使用HttpClient发送请求接收响应
1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...
随机推荐
- git使用流程
1,配置sshkey: ssh-keygen -t rsa -C "Github 的注册邮箱" //创建本地 ssh 在 Github 中添加这个 sshkey : 复制 id_ ...
- CentOS 配置 iptables 配合 ss
转自:http://www.jianshu.com/p/28b8536a6c8a 环境: CentOS 6 shadowsocks iptables 在安装了ss-bash后,ss-bash每添加一次 ...
- python set集合操作
set集合是一个无序且不重复的集合. 创建一个set集合: name = set('sdd') name 返回结果:{'d', 's'} add 功能:增加集合元素 name = {'d', 's'} ...
- WPF外包公司——北京动点飞扬软件:开发企业WPF项目需要掌握些什么
做为企业开发一个WPF项目,对于很多不熟悉微软WPF技术和XAML语言开发团队而言,北京动点飞扬在此给各位一点建议: 1.首先开发团队要整体对于XAML和WPF的运作机制熟悉. 2.开发人员起码要会用 ...
- Android开发艺术探索读书笔记——01 Activity的生命周期
http://www.cnblogs.com/csonezp/p/5121142.html 新买了一本书,<Android开发艺术探索>.这本书算是一本进阶书籍,适合有一定安卓开发基础,做 ...
- MapReduce格式与类型
MapReduce Types MapReduce是一个简单的数据处理模型,map与reduce的输入和输出类型都为key-value形式的键值对. map: (K1, V1) → list(K2, ...
- Codeforces 721D [贪心]
/* 不要低头,不要放弃,不要气馁,不要慌张. 题意: 给一列数a,可以进行k次操作,每次操作可以选取任意一个数加x或者减x,x是固定的数.求如何才能使得这个数列所有数乘积最小. 思路: 贪心...讨 ...
- 【转】CwRsync简介
rsync是linux下一款用于同步文件的优秀软件,window下也可以使用它,不过名字为cwRsync.cwRsync也分为客户端和服务端,官方网址:https://www.itefix.no/i2 ...
- C#EXCEL 操作类--C#ExcelHelper操作类
主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...
- jmeter的逻辑控制器
这篇是在网上找的,写的实在是比我写的具体得多,也没什么好补充的,拿来记录一下,方便以后查询,感激原作者!! JMeter中的Logic Controller分为两类:一类用来控制Test Plan执行 ...