Java 发送http post 请求
package com.sm.utils; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; public class HttpUtils {
public static final String CHARSET = "UTF-8";
// 发送get请求 url?a=x&b=xx形式
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlName = "";
if (param.length() != ) {
urlName = url + "?" + param;
} else
urlName = url;
URL resUrl = new URL(urlName);
URLConnection urlConnec = resUrl.openConnection();
urlConnec.setRequestProperty("accept", "*/*");
urlConnec.setRequestProperty("connection", "Keep-Alive");
urlConnec.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
urlConnec.connect();
Map<String, List<String>> map = urlConnec.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(urlConnec.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送get请求失败" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
} // 发送post请求
public static String sendPost(String url, MultipartHttpServletRequest param) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL resUrl = new URL(url);
URLConnection urlConnec = resUrl.openConnection();
urlConnec.setRequestProperty("accept", "*/*");
urlConnec.setRequestProperty("connection", "Keep-Alive");
urlConnec.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
urlConnec.setDoInput(true);
urlConnec.setDoOutput(true); out = new PrintWriter(urlConnec.getOutputStream());
out.print(param);// 发送post参数
out.flush();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(urlConnec.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("post请求发送失败" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
} //post请求方法
public static String sendPost(String url, Map<String,Object> params) {
String response = null;
System.out.println(url);
System.out.println(params);
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
// StringEntity stringentity = new StringEntity(data);
if (pairs != null && pairs.size() > ) {
httppost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
httpresponse = httpclient.execute(httppost);
response = EntityUtils
.toString(httpresponse.getEntity());
System.out.println(response);
} finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("id","");
sendPost("http://192.168.1.56:8080/smkj/api/lcds/user/lcdsUser",map);
}
/**
* 测试
* 说明:这里用新浪股票接口做get测试,新浪股票接口不支持jsonp,至于post,因为本人用的公司的接口就不展示了,一样的,一个url,一个数据包
*/
/*
* public static void main(String[] args) { // TODO Auto-generated method
* stub String resultGet = sendGet("http://hq.sinajs.cn/list=sh600389","");
* System.out.println(resultGet); }
*/ }
Java 发送http post 请求的更多相关文章
- Java发送HTTP POST请求示例
概述: http请求在所有的编程语言中几乎都是支持的,我们常用的两种为:GET,POST请求.一般情况下,发送一个GET请求都很简单,因为参数直接放在请求的URL上,所以,对于PHP这种语言,甚至只需 ...
- java发送http get请求的两种方式
长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) thro ...
- java 发送get,post请求
package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStr ...
- Java发送HTTP POST请求(内容为xml格式)
今天在给平台用户提供http简单接口的时候,顺便写了个调用的Java类供他参考. 服务器地址:http://5.0.217.50:17001/VideoSend 服务器提供的是xml格式的h ...
- java 发送http json请求
public void getRemoteId(HttpServletRequest request,Model model){ String name = request.getParameter( ...
- JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理
java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...
- Java发送Http请求并获取状态码
通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...
- 编写爬虫(spider)的预备知识:用java发送HTTP请求
使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...
- 通过java发送http请求
通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...
随机推荐
- POJ 3281 Dining (网络流)
POJ 3281 Dining (网络流) Description Cows are such finicky eaters. Each cow has a preference for certai ...
- java Random.nextInt()方法
转: java Random.nextInt()方法 lic int nextInt(int n) 该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含 ...
- debian8.4 系统莫名没有声音
[http://www.linuxdiyf.com/viewarticle.php?id=437020 Debian8, 桌面环境是xfce4, 安装完成后发现前面板音频输出插孔正常,后面板的没声音. ...
- Centos7搭建SS以及加速配置的操作记录
部署 Shadowsocks之前,对它做了一个简单的了解,下面先介绍下.一道隐形的墙众所周知,天朝局域网通过 GFW (中国防火墙长城:英文名称Great Firewall of China,简写为G ...
- Hadoop生态圈-zookeeper本地搭建以及常用命令介绍
Hadoop生态圈-zookeeper本地搭建以及常用命令介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.下载zookeeper软件 下载地址:https://www.ap ...
- mongodb与mysql的区别与具体应用场景
MongoDB: 非关系型数据库,文档型数据库, 文档型数据库:可以存放xml,json,bson类型的数据.这些数据具备自述性(self-describing),呈现分层的树状数据结构.数据结构由键 ...
- C#获取文件超大图标256*256(转)
从Bing搜索得到,保存于此 using System; using System.Collections.Generic; using System.Linq; using System.Text; ...
- bzoj千题计划278:bzoj4590: [Shoi2015]自动刷题机
http://www.lydsy.com/JudgeOnline/problem.php?id=4590 二分 这么道水题 没long long WA了两发,没判-1WA了一发,二分写错WA了一发 最 ...
- js 正则学习小记之匹配字符串字面量优化篇
昨天在<js 正则学习小记之匹配字符串字面量>谈到 个字符,除了第一个 个,只有 个转义( 个字符),所以 次,只有 次成功.这 次匹配失败,需要回溯后用 [^"] 才能匹配成功 ...
- yii2框架目录
框架目录结构 [目录] backend——后台web程序 common——公共的文件 console——控制台程序 environments——环境配置 frontend——前台web程序 [文件] ...