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.IOException; im ...
- [笨木头FireFly 02]入门篇2_客户端发送请求,服务器处理请求
原地址:http://www.9miao.com/question-15-53940.html 好,经过上一篇不权威的讲解,大家已经能轻易地让客户端和服务端连接起来了. 但是,仅仅是连接了,可它们俩不 ...
- 使用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 ...
随机推荐
- PHP利用GD库处理图片方法实现
这里写的是完成每个功能的函数,可以复制单个函数直接使用,这里的每个函数都是另外一篇PHP常用类------图片处理类Image当中的方法进行细化,可以参考一下 废话不多说,直接付代码吧! 添加水印(文 ...
- QQ的小秘密
http://ssl.ptlogin2.qq.com/test http://ping.huatuo.qq.com/ http://localhost.ptlogin2.qq.com:4300/mc_ ...
- [cnblog新闻]阿里的营业利润3倍于亚马逊,但为何市值只是亚马逊的一半?
阿里的营业利润3倍于亚马逊,但为何市值只是亚马逊的一半? 投递人 itwriter 发布于 2019-01-26 16:52 评论(0) 有688人阅读 原文链接 [收藏] « » http://ww ...
- 转帖 Oracle 主键的处理方法 http://www.cnblogs.com/Richardzhu/p/3470929.html
Oracle之主键的创建.添加.删除操作 一.创建表的同时创建主键约束 1.1.无命名 SQL> create table jack (id int primary key not null ...
- python3_列表、元组、集合、字典
列表list #列表的基本操作 >>> a=[] #创建空列表 >>> a = [0,1,2,3,4,5] #创建列表并初始化,列表是[]包含由逗号分隔的多个元素组 ...
- NodeJS中的require和import
ES6标准发布后,module成为标准,标准的使用是以export指令导出接口,以import引入模块,但是在我们一贯的node模块中,我们采用的是CommonJS规范,使用require引入模块,使 ...
- python学习笔记十——模块与函数
第五章 模块与函数 5.1 python程序的结构 函数+类->模块 模块+模块->包 函数+类+模块+包=Python pyth ...
- 设计模式笔记:策略模式(Strategy)
1. 策略模式简介 1.1 定义 策略是为达到某一目的而采取的手段或方法,策略模式的本质是目标与手段的分离,手段不同而最终达成的目标一致.客户只关心目标而不在意具体的实现方法,实现方法要根据具体的环境 ...
- 理解 Delphi 的类(十) - 深入方法[18] - 在接口区声明的方法都相当于提前声明了
//要点18: 如果函数在接口区定义了, 就无需用 forward 提前声明了 unit Unit1; interface uses Windows, Messages, SysUtils, Va ...
- html 佈局
html常見佈局方式有以下幾種: 1.使用div的html 利用div可以為html實現多列佈局. 2.使用html5的網站佈局, 利用html新增的header.footer.nav.section ...