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 ...
随机推荐
- HTML 页面的 批量删除的按钮
function delAll(){ var sid=""; $("[name='ids']:checked").each(function(){ sid+=$ ...
- PAT 1036 跟奥巴马一起编程
https://pintia.cn/problem-sets/994805260223102976/problems/994805285812551680 美国总统奥巴马不仅呼吁所有人都学习编程,甚至 ...
- OpenCV Code: Operations on Mat element
cv::Mat img = cv::imread("image.jpg"); Method 1: img.at<uchar>(i, j, k) Method 2: im ...
- Node 多页面请求
//功能:创建web服务器接收客户请求// http://127.0.0.1:8080/index 准备// http://127.0.0.1:8080/news 准备// public/index. ...
- React 表单受控组件
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- js 錯誤
try{ //需要被檢測是否拋出錯誤 } catch(err) { //錯誤處理代碼 } try.catch成對出現 throw:拋出錯誤 當錯誤發生時,javascript引擎停止運行,并生成一個錯 ...
- MySQL基本概念以及简单操作
一.MySQL MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MyS ...
- unwrap bug
https://cn.mathworks.com/matlabcentral/newsreader/view_thread/93276
- Check failed: status == CUBLAS_STATUS_SUCCESS (11 vs. 0) CUBLAS_STATUS_MAPPING_ERROR
I0930 21:23:15.115576 30918 solver.cpp:281] Learning Rate Policy: multistepF0930 21:23:17.263314 310 ...
- @classmethod 与 @staticmethod 区别