java中发送http请求的方法
package org.jeecgframework.test.demo;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Set;
import java.util.SortedMap; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; public class HttpClientHelper {
/**
* @Description:使用HttpURLConnection发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:26:07
*/
public static String sendPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
// 发送请求
try {
URL url = new URL(urlParam);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (sbParams != null && sbParams.length() > 0) {
osw = new OutputStreamWriter(con.getOutputStream(), charset);
osw.write(sbParams.substring(0, sbParams.length() - 1));
osw.flush();
}
// 读取返回内容
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
} return resultBuffer.toString();
} /**
* @Description:使用HttpClient发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:28:23
*/
public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlParam);
// 构建请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> elem = iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
BufferedReader br = null;
try {
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = client.execute(httpPost);
// 读取服务器响应数据
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} //请求xml组装
public static String getRequestXml(SortedMap<String,Object> parameters){
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {
sb.append("<"+key+">"+"<![CDATA["+value+"]]></"+key+">");
}else {
sb.append("<"+key+">"+value+"</"+key+">");
}
}
sb.append("</xml>");
return sb.toString();
}
//生成签名
public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + "");
String sign = MD5.md5(sb.toString()).toUpperCase();
return sign;
}
//请求方法
public static String httpsRequest(String requestUrl, String requestMethod, String data) {
try { URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/json");
// conn.setRequestProperty("content-type", "text/xml;charset=utf-8");
// 当outputStr不为null时向输出流写数据
if (null != data) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("连接超时:{}"+ ce);
} catch (Exception e) {
System.out.println("https请求异常:{}"+ e);
}
return null;
}
public static void main(String[] args) {
String requestUrl,requestMethod,outputStr;
requestUrl="(此处填写你要请求的url地址)";
requestMethod="POST";
outputStr="<xml>"+
"<appid><![CDATA[wx2421b1c4370ec43b]]></appid>"+
"<mch_id><![CDATA[10000100]]></mch_id>"+
"<device_info><![CDATA[1]]></device_info>"+
"<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>"+
"<sign><![CDATA[6245928B869A39BC75A421200A74002E]]></sign>"+
"<result_code><![CDATA[SUCCESS]]></result_code>"+
"<return_code><![CDATA[SUCCESS]]></return_code>"+
"<err_code><![CDATA[1004400740201409030005092168]]></err_code>"+
"<err_code_des><![CDATA[1004400740201409030005092168]]></err_code_des>"+
"<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>"+
"<is_subscribe><![CDATA[Y]]></is_subscribe>"+
"<trade_type><![CDATA[JSAPI]]></trade_type>"+
"<bank_type><![CDATA[CFT]]></bank_type>"+
"<total_fee><![CDATA[1]]></total_fee>"+
"<fee_type><![CDATA[CNY]]></fee_type>"+
"<cash_fee><![CDATA[168]]></cash_fee>"+
"<cash_fee_type><![CDATA[1004400740201409030005092168]]></cash_fee_type>"+
"<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>"+
"<out_trade_no><![CDATA[137999992017032919767558710]]></out_trade_no>"+
"<time_end><![CDATA[20140903131540]]></time_end>"+
"<trade_state><![CDATA[1]]></trade_state>"+
"<attach><![CDATA[支付测试]]></attach>"+
"</xml>"; //错误的json请求
// String data = "[{\"id\":1,\"name\":\"o2o_V3.0新版发布\",\"content\":\"o2o_V3.0新版发布\",\"time\":\"2015-05-11 03:12:51\"}]";
String data = "{\"id\":1,\"name\":\"o2o_V3.0新版发布\",\"content\":\"o2o_V3.0新版发布\",\"time\":\"2015-05-11 03:12:51\"}";
String xml=httpsRequest(requestUrl,requestMethod,data);
System.out.println(xml);
//System.out.println(outputStr);
} }
请求的时候只需要调用这个类中的httpsRequest方法,requestUrl代表的就是请求的url地址,requestMethod代表的是以Post或者Get方法请求方式,data就是请求的参数;
java中发送http请求的方法的更多相关文章
- 发送http请求的方法
在http/1.1 协议中,定义了8种发送http请求的方法 get post options head put delete trace connect patch. 根据http协议的设计初衷,不 ...
- Vue中发送ajax请求——axios使用详解
axios 基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用 功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 htt ...
- Java 中extends与implements使用方法
Java 中extends与implements使用方法 标签: javaclassinterfacestring语言c 2011-04-14 14:57 33314人阅读 评论(7) 收藏 举报 分 ...
- Java中的equals和hashCode方法
本文转载自:Java中的equals和hashCode方法详解 Java中的equals方法和hashCode方法是Object中的,所以每个对象都是有这两个方法的,有时候我们需要实现特定需求,可能要 ...
- java httpclient发送json 请求 ,go服务端接收
/***java客户端发送http请求*/package com.xx.httptest; /** * Created by yq on 16/6/27. */ import java.io.IOEx ...
- Java中各种(类、方法、属性)访问修饰符与修饰符的说明
类: 访问修饰符 修饰符 class 类名称 extends 父类名称 implement 接口名称 (访问修饰符与修饰符的位置可以互换) 访问修饰符 名称 说明 备注 public 可以被本项目的所 ...
- Java中替换HTML标签的方法代码
这篇文章主要介绍了Java中替换HTML标签的方法代码,需要的朋友可以参考下 replaceAll("\\&[a-zA-Z]{0,9};", "").r ...
- java中需要关注的3大方面内容/Java中创建对象的几种方法:
1)垃圾回收 2)内存管理 3)性能优化 Java中创建对象的几种方法: 1)使用new关键字,创建相应的对象 2)通过Class下面的new Instance创建相应的对象 3)使用I/O流读取相应 ...
- Java中字符串的一些常见方法
1.Java中字符串的一些常见方法 /** * */ package com.you.model; /** * @author Administrator * @date 2014-02-24 */ ...
随机推荐
- oralce ROLLUP
select id,area,stu_type,sum(score) score from students group by rollup(id,area,stu_type) order by id ...
- 创建ROS 工作空间时出现:程序“catkin_init_workspace”尚未安装,程序“catkin_make”尚未安装。
问题:创建ROS 工作空间时出现:程序“catkin_init_workspace”尚未安装,程序“catkin_make”尚未安装. 解决方法: source /opt/ros/kinetic/se ...
- js280行代码写2048
2048 原作者就是用Js写的,一直想尝试.但久久未动手. 昨天教学生学习JS代码.最好还是就做个有趣的游戏好了.2048这么火,是一个不错的选择. 思路: 1. 数组 ,2维数组4x4 2. 移动算 ...
- 洛谷P1049 装箱问题
//01背包 价值等于体积 求所剩最小体积 #include<bits/stdc++.h> using namespace std; ; ; int c,n,v[maxn],f[maxv] ...
- 06Redis入门指南笔记(安全、通信协议、管理工具)
一:安全 1:可信的环境 Redis以简洁为美.在安全层面Redis也没有做太多的工作.Redis的安全设计是在"Redis运行在可信环境"这个前提下做出的.在生产环境运行时不能允 ...
- Android读取sd卡
public static String[] getStoragePaths() { List<String> pathsList = new ArrayList<String> ...
- ansible api 通过python 方式调用
pip3 install ansible Linux下面安装 Windows 安装没成功 from ansible.parsing.dataloader import DataLoader #读取ya ...
- 一文告诉你Adam、AdamW、Amsgrad区别和联系 重点
**序言:**Adam自2014年出现之后,一直是受人追捧的参数训练神器,但最近越来越多的文章指出:Adam存在很多问题,效果甚至没有简单的SGD + Momentum好.因此,出现了很多改进的版本, ...
- Laravel 之搜索引擎elasticsearch扩展Scout
简介 Laravel Scout 是针对Eloquent 模型开发的一个简单的,基于驱动的全文检索系统.Scout 使用模型观察者时会自动保持你的检索索引与你的 Eloquent 记录同步. 目前,S ...
- torch.optim优化算法理解之optim.Adam()
torch.optim是一个实现了多种优化算法的包,大多数通用的方法都已支持,提供了丰富的接口调用,未来更多精炼的优化算法也将整合进来. 为了使用torch.optim,需先构造一个优化器对象Opti ...