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请求 ...
随机推荐
- list All elements are null引起的异常
ArrayList允许添加null值,就容易造成了list内的对象转换出现java.lang.NullPointerException异常. 场景: 数据库 select min(id) as id ...
- CodeForces 450B Jzzhu and Sequences (矩阵优化)
CodeForces 450B Jzzhu and Sequences (矩阵优化) Description Jzzhu has invented a kind of sequences, they ...
- Java基本语法---个人参考资料
Java语言基础组成:关键字.标识符.注释.常量和变量.运算符.语句.函数.数组 一.标识符 标识符是在程序中自定义的一些名称,由大小写字母[a-zA-Z],数字[0-9],下划线[ _ ],特殊字符 ...
- C#获取文件超大图标256*256(转)
从Bing搜索得到,保存于此 using System; using System.Collections.Generic; using System.Linq; using System.Text; ...
- Tomcat——Linux下的安装和配置
Tomcat在Linux上的安装与配置 以下使用的Linux版本为: Redhat Enterprise Linux 7.0 x86_64,Tomcat版本为tomcat-7.0.54. 1.下载JD ...
- POJ 2932 圆扫描线
求n个圆中没有被包含的圆.模仿扫描线从左往右扫,到左边界此时如有3个交点,则有3种情况,以此判定该圆是否被离它最近的圆包含,而交点和最近的圆可以用以y高度排序的Set来维护.因此每次到左边界插入该圆, ...
- 干货:制作科研slide简明规范
- MySQL异步复制延迟解决
http://www.ttlsa.com/mysql/mysql-5-7-enhanced-multi-thread-salve/
- 【两分钟教程】如何更改Xcode项目名称
注意:视频在最后,还少了一个步骤:将Xcode中的名字叫做<企信通>的虚拟文件夹删掉,然后重新从硬盘中添加进来,这样就彻底完成了更改Xcode项目名称的目的.
- CSS position:absolute浅析
一.绝对定位的特征 绝对定位有着与浮动一样的特性,即包裹性和破坏性. 就破坏性而言,浮动仅仅破坏了元素的高度,保留了元素的宽度:而绝对定位的元素高度和宽度都没有了. 请看下面代码: <!DOCT ...