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对 ...
随机推荐
- CSS3 动画基础
该文为译文转载,原文地址:http://tech.163.com/mobile/10/0106/09/5SB96QSM00112K88.html 译文:你需要知道的CSS3 动画技术 原文:Wha ...
- Python中optionParser模块的使用方法[转]
本文以实例形式较为详尽的讲述了Python中optionParser模块的使用方法,对于深入学习Python有很好的借鉴价值.分享给大家供大家参考之用.具体分析如下: 一般来说,Python中有两个内 ...
- Java--RuntimeException(运行时异常)
[转载自]:http://blog.csdn.net/qq7342272/article/details/7940741 java运行时异常是可能在java虚拟机正常工作时抛出的异常. java提供了 ...
- RestEasy 3.x 系列之一:Hello world
RestEasy 3.x改了不少,走了好多弯路才终于搞出来,做做笔记,陆续发布…… tomcat-7.0.50 java version "1.7.0_51" myeclipse ...
- Docker SSH
1. Dockerfile -->docker build -t centos6-ssh https://git.oschina.net/feedao/Docker_shell/raw/st ...
- MongoDB 备份(mongodump)恢复(mongorerstore) 导出 (Mongoexport) 导入( Mongoimport)
MongoDB 备份(mongodump) 在Mongodb中我们使用mongodump命令来备份MongoDB数据.该命令可以导出所有数据到指定目录中. mongodump命令可以通过参数指定导出的 ...
- 是不是content-type: text/html的数据包一到,浏览器就肯定刷新页面?
整理自:http://q.cnblogs.com/q/54726/ 是不是content-type: text/html的数据包一到,浏览器就肯定刷新页面? 或者说,浏览器收到的状态正常的conten ...
- UILabel的使用
UILabel是iOS用于显示文本的控件. 基本属性如下代码所示: UILabel *lbl = [[UILabel alloc] init] ; //设置显示区域 lbl.frame = CGRec ...
- LVS的四种模式的实现
LVS 是四层负载均衡,也就是说建立在 OSI 模型的第四层——传输层之上,传输层上有我们熟悉的 TCP/UDP,LVS 支持 TCP/UDP 的负载均衡. LVS 的转发主要通过修改 IP 地址(N ...
- Provisional, Temporary 和Interim 的区别
1 Provisional adj. 临时的.暂时的.暂定的:n. 临时邮票 强调在一定时期内暂时的.双方同意的但还不是最终确定的决定或者条约等. Such as例如: Provisional go ...