java通过java.net.URL发送http请求调用接口
一般在*.html,*.jsp页面中我们通过使用ajax调用接口,这个是我们通常用的。对于这些接口,大都是本公司写的接口供自己调用,所以直接用ajax就可以。但是,如果是多家公司共同开发一个东西,一个功能可能要调多个接口,一两个ajax可以在jsp页面上显示,但是如果多了,就不能写这么多ajax在前端了。这时候需要封装一成一个接口,在接口里面如何调用其他接口呢?这就用到了java.net.URL这个类。
java.net.URL用法如下
BufferedReader in=null;
java.net.HttpURLConnection conn=null;
String msg = "";// 保存调用http服务后的响应信息
try
{
//实例化url
java.net.URL url = new java.net.URL(path);
//根据url获取HttpURLConnection
conn = (java.net.HttpURLConnection) url.openConnection();
//设置请求的参数
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);// 设置连接超时时间为5秒
conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
conn.setDoOutput(true); // 使用 URL 连接进行输出,则将 DoOutput标志设置为 true
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//conn.setRequestProperty("Content-Encoding","gzip");
conn.setRequestProperty("Content-Length", String.valueOf(params.length())); //设置请求内容(长度)长度
OutputStream outStream = conn.getOutputStream(); // 返回写入到此连接的输出流
outStream.write(params.getBytes()); //将参数写入流中
outStream.close();//关闭流 if (conn.getResponseCode() == 200) {
// HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码
in = new BufferedReader(new InputStreamReader((InputStream) conn.getInputStream(), "UTF-8"));
msg = in.readLine();
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally
{
if(null!=in)
{
in.close();
}
if(null!=conn)
{
conn.disconnect();
}
}
return msg;
HttpUtil工具类
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.net.HttpURLConnection;
import java.net.URL; /**
* http工具
*
*/
public final class HttpUtil {
/**
* 模拟http协议发送get请求
**/
public static String sendGetRequest(String url) {
String result = "";
InputStream in = null; HttpURLConnection connection = null; try {
URL httpUrl = new URL(url);
connection = (HttpURLConnection) httpUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestMethod("GET");
connection.connect(); if (connection.getResponseCode() == 200) {
in = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream();
int n = 0;
byte[] datas = new byte[2048]; while ((n = in.read(datas)) != -1) {
bs.write(datas, 0, n);
} bs.flush();
result = new String(bs.toByteArray(), "utf-8");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} try {
connection.disconnect();
} catch (Exception ex) {
}
} return result;
} /**
* 模拟http协议发送post请求
**/
public static String sendPostRequest(String url, String param) {
InputStream in = null;
String result = "";
HttpURLConnection connection = null; try {
URL httpUrl = new URL(url);
connection = (HttpURLConnection) httpUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.getOutputStream().write(param.getBytes("utf-8"));
connection.getOutputStream().flush(); if (connection.getResponseCode() == 200) {
in = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream();
int n = 0;
byte[] datas = new byte[2048]; while ((n = in.read(datas)) != -1) {
bs.write(datas, 0, n);
} bs.flush();
result = new String(bs.toByteArray(), "utf-8");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} try {
connection.disconnect();
} catch (Exception ex) {
}
} return result;
} /**
* 普通post文件上传
*/
public static String upLoadAttachment(String url, String fileName, File file) {
String result = null; HttpURLConnection connection = null;
BufferedReader reader = null; try {
URL httpUrl = new URL(url);
connection = (HttpURLConnection) httpUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false); String bound = "----------" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + bound); StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(bound);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"" + fileName +
"\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(data); DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
} in.close(); byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定义最后数据分隔线
out.write(foot);
out.flush();
out.close(); InputStream inn = connection.getInputStream();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int n = 0;
byte[] datas = new byte[2048]; while ((n = inn.read(datas)) != -1) {
bs.write(datas, 0, n);
} bs.flush();
result = new String(bs.toByteArray(), "utf-8"); return result;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
connection.disconnect();
} catch (Exception ex) {
}
} return null;
} /**
* post文件上传 - 使用InputStream输入流(例如MultipartFile从前端获取文件后转发给其他的服务器)
*/
public static String upLoadAttachment(String url,String keyName, String fileName, InputStream fins) {
String result = null; HttpURLConnection connection = null;
BufferedReader reader = null; try {
URL httpUrl = new URL(url);
connection = (HttpURLConnection) httpUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false); String bound = "----------" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + bound); StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(bound);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"" + keyName +
"\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes("utf-8");
OutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(data); DataInputStream in = new DataInputStream(fins);
int bytes = 0;
byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
} in.close(); byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定义最后数据分隔线
out.write(foot);
out.flush();
out.close(); InputStream inn = connection.getInputStream();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int n = 0;
byte[] datas = new byte[2048]; while ((n = inn.read(datas)) != -1) {
bs.write(datas, 0, n);
} bs.flush();
result = new String(bs.toByteArray(), "utf-8"); return result;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
connection.disconnect();
} catch (Exception ex) {
}
} return null;
}
}
java通过java.net.URL发送http请求调用接口的更多相关文章
- Java发布webservice应用并发送SOAP请求调用
webservice框架有很多,比如axis.axis2.cxf.xFire等等,做服务端和做客户端都可行,个人感觉使用这些框架的好处是减少了对于接口信息的解析,最主要的是减少了对于传递于网络中XML ...
- JAVA使用apache http组件发送POST请求
在上一篇文章中,使用了JDK中原始的HttpURLConnection向指定URL发送POST请求 可以看到编码量有些大,并且使用了输入输出流 传递的参数还是用“name=XXX”这种硬编的字符串进行 ...
- python接口自动化(八)--发送post请求的接口(详解)
简介 上篇介绍完发送get请求的接口,大家必然联想到发送post请求的接口也不会太难,被聪明的你又猜到了.答案是对的,虽然发送post请求的参考例子很简单,但是实际遇到的情况却是很复杂的,因为所有系统 ...
- 发送post请求的接口
一.简介 所有系统或者软件.网站都是从登录开始,所以首先介绍的第一个post请求是登录. 二.help函数 学习一个新的模块捷径,直接用help()函数查看相关注释和案例内容 for example: ...
- Hbuilder MUI里面使用java.net.URL发送网络请求,操作cookie
1. 引入所需网络请求类: var URL = plus.android.importClass("java.net.URL"); var URLConnection = plus ...
- 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)
Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...
- 向指定URL 发送POST请求的方法
java发送psot请求: package com.tea.web.admin; import java.io.BufferedReader; import java.io.IOException; ...
- java编程(2)——servlet和Ajax异步请求的接口编程(有调用数据库的数据)
第一步: 1.为项目配置 Tomcat 为 server: 2.导入 mysql的jar包 到项目目录中: 第二步:编码 1.数据库连接类ConnectMysql.java代码: package co ...
- 对WEB url 发送POST请求
package com.excellence.spark; import java.util.List; import com.excellence.spark.test.test; import c ...
随机推荐
- Python:re.sub()实现字符串替换
re.sub的功能 re是regular expression的缩写,表示正则表达式:sub是substitude的缩写,表示替换 re.sub是正则表达式的函数,实现比普通字符串更强大的替换功能 s ...
- GDPR给安全的影响
违反GDPR的代价过于巨大,因而你不得不为那些预料不到的后果考虑,而且因为无法使用Whois数据,无形中也扩大了威胁界面.因为GDPR的存在,可供黑客入侵的威胁界面显著增长,不是增加了一点点,而是翻了 ...
- MySQL Crash Course #03# Chapter 5. 6 排序. BETWEEN. IS NULL
索引 排序检索的数据 SQL 过滤 vs. 应用程序过滤 简单 Where 补充:大小写敏感. BETWEEN. IS NULL Sorting Retrieved Data mysql> SE ...
- PHP多进程处理并行处理任务实例(转,备用)
本文目的本文通过例子讲解linux环境下,使用php进行并发任务处理,以及如何通过pipe用于进程间的数据同步.PHP多进程通过pcntl_XXX系列函数使用多进程功能.注意:pcntl_XXX只能运 ...
- 04: Mysql性能优化
MySQL其他篇 目录: 参考网站 1.1 Mysql数据库的优化技术 1.2 数据库表设计 1.3 SQL优化 1.为查询缓存优化你的查询 2.EXPLAIN 你的 SELECT 查询 3. 当只要 ...
- 20145106《Java程序设计》第7周学习总结
教材学习内容总结 使用Lambda的特性可以去除重复的信息,以取得语法的简洁,增加程序代码的表达性.Lambda表达式本身是中性的,不代表任何类型的实例,同样的Lambda表达式,可用来表示不同目标类 ...
- 20145310《网络对抗》逆向及Bof基础
实践目标 本次实践的对象是一个名为pwn1的linux可执行文件. 该程序正常执行流程是:main调用foo函数,foo函数会简单回显任何用户输入的字符串. 该程序同时包含另一个代码片段,getShe ...
- 2018-2019-1 1723《程序设计与数据结构》第5&6&7周作业 总结
作业地址 第五周作业: 提交情况如图: 第六周作业: 提交情况如图: 第七周作业: 提交情况如图: 作业问题 很多看上写的比较详细并且语言组织的也不错,我就这么随手一百度,搜出来了很多篇博客.(无奈) ...
- C# string字节数组转换
string转byte[]:byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str ); byte[]转string:string ...
- Linux系统编程之--守护进程的创建和详解【转】
本文转载自:http://www.cnblogs.com/mickole/p/3188321.html 一,守护进程概述 Linux Daemon(守护进程)是运行在后台的一种特殊进程.它独立于控制终 ...