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 */ ...
随机推荐
- Alternating Direction Method of Multipliers -- ADMM
前言: Alternating Direction Method of Multipliers(ADMM)算法并不是一个很新的算法,他只是整合许多不少经典优化思路,然后结合现代统计学习所遇到的问题,提 ...
- Libev源码分析08:Libev中的信号监视器
Libev中的信号监视器,用于监控信号的发生,因信号是异步的,所以Libev的处理方式是尽量的将异步信号同步化.异步信号的同步化方法主要有:signalfd.eventfd.pipe.sigwaiti ...
- phpmyadmin设置自动登录和取消自动登录
1首先在phpmyadmin安装目录下找到config.sample.inc.php复制一份文件名改为config.inc.php 2打开config.inc.php 找到 $cfg['Serve ...
- hdu 3339 In Action(迪杰斯特拉+01背包)
In Action Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ...
- cf1234-div3
A 水题 B 直接看2,发现`unordered_map被卡了...` 乖乖离散化 C 有六种水管,可以任意的旋转,使得有一条从(1, 0)到(2, n)的通路. 找规律,当时写D没来得及看 #inc ...
- mac上的mysql管理工具sequel pro
https://blog.csdn.net/wan_zaiyunduan/article/details/54909389 以前用过Plsql.Navicat.Workbench,现在换到mac上,用 ...
- Python--day68--Django ORM常用字段、不常用的字段、自定义字段
ORM和数据库的对应关系: Django ORM 常用字段和参数 常用字段 AutoField int自增列,必须填入参数 primary_key=True.当model中如果没有自增列,则自动会创建 ...
- HDU 1051
题意:给你n个木块的长和宽,现在要把它送去加工,这里怎么说呢,就是放一个木块花费一分钟,如果后面木块的长和宽大于等于前面木块的长和宽就不需要花费时间,否则时间+1,问把这个木块送去加工的最短时间. 思 ...
- H3C Basic NAT配置示例
- [转]ECMAScript 2016,2017 和 2018 中所有新功能的示例
很难追踪 JavaScript(ECMAScript)中的新功能. 想找到有用的代码示例更加困难. 因此,在本文中,我将介绍 TC39 已完成 ES2016,ES2017 和 ES2018(最终草案) ...