笔记,未完全标准.

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 发送请求范例的更多相关文章

  1. URLConnection 和 HttpClients 发送请求范例【原】

    笔记,未完全标准. java.net.URLConnection package test; import java.io.BufferedReader; import java.io.IOExcep ...

  2. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

  3. spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

    在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实 ...

  4. ajax发送请求跨域 - uri java代理

    问题:ajax发送请求出现cors跨域 解决办法:可以通过java代理的方式,后台发送请求 1.get请求 public void proxyGet(String url) { try { URL r ...

  5. java后台发送请求并获取返回值

    项目中需要前端发送请求给后端,而后端需要从另一个平台中取数据然后再透传给前端,通过下述代码将其实现.在此记录一下. package com.autotest.utils; import java.io ...

  6. java后端发送请求

    package com.ty.mapapisystem.util; import java.io.BufferedReader;import java.io.FileInputStream;impor ...

  7. 使用HttpClient配置代理服务器模拟浏览器发送请求调用接口测试

    在调用公司的某个接口时,直接通过浏览器配置代理服务器可以请求到如下数据: 请求url地址:http://wwwnei.xuebusi.com/rd-interface/getsales.jsp?cid ...

  8. java后台向路径发送请求获得相应参数

    从java后台向一路径发送请求,获得响应的参数,put get post ,还有一个返回URL的工具类,方便代码灵活修改 import java.io.BufferedReader; import j ...

  9. 使用HttpClient发送请求接收响应

    1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...

随机推荐

  1. 区间更新 zoj3911

    哎,没什么坑点,一个简单的区间更新题,但是改了好几天没改对,最终还是过了~~发个纪念下 泪奔... #include<cstdio>#include <iostream>#in ...

  2. Learning to write a compiler

    http://stackoverflow.com/questions/1669/learning-to-write-a-compiler?rq=1 Big List of Resources: A N ...

  3. lua学习记录

    1.八种数据类型:number,string,boolean,nil,function,table,协程,自定义类型 空字符串和数字0是真,false和nil为假2.lua是动态语言,每个变量携带自己 ...

  4. 如果在代码中使用JS

    protected void Page_Load(object sender, EventArgs e)    {        //获得.js文件        string myscript = ...

  5. python Data type conversation

    >>> repr(111.5) '111.5' >>> repr(10) ' >>> int(") 11 >>> lo ...

  6. [Spring MVC] - Spring MVC环境搭建

    1) 复制Spring所需要的lib包         (这是SSH所需要的lib包,如果只使用spring,可以移除一些包) 2) 配置web.xml <?xml version=" ...

  7. webpack +vue开发(1)

    首先安装 node.js这是毋庸置疑的,安装完了之后安装webpack npm install webpack -g 接下来创建一个自己的文件夹 webpack-learn在里面创建一个index.h ...

  8. [家里蹲大学数学杂志]第033期稳态可压Navier-Stokes方程弱解的存在性

    1. 方程  考虑 $\bbR^3$ 中有界区域 $\Omega$ 上如下的稳态流动: $$\bee\label{eq} \left\{\ba{ll} \Div(\varrho\bbu)=0,\\ \ ...

  9. java 进程启用远程查看

    用jconsole 1.启动脚本增加: JAVA_OPTS="-Djava.net.preferIPv4Stack=true -Djava.rmi.server.hostname=192.1 ...

  10. 立体匹配:关于用OpenCV彩色化middlebury网站给定的视差

    #include "XYZ.h" void readPFM(Mat_<float> &disp, float &scale, string path) ...