Http请求get和post调用
工作中会遇到远程调用接口,需要编写Http请求的共通类
以下是自己总结的Http请求代码
package com.gomecar.index.common.utils; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*; public class HttpUtils { /**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param timeout 连接超时时间 /单位毫秒
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param,int timeout) {
StringBuffer resultBuf = new StringBuffer(); BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
// connection.setRequestProperty("accept", "*/*");
// connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(timeout);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String line;
while ((line = in.readLine()) != null) {
resultBuf.append(line);
}
} catch (Exception e) {
// System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return resultBuf.toString();
} public static String assemParam(Map<String, Object> param) {
Set<String> keys = param.keySet();
StringBuffer sb = new StringBuffer();
for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
String key = iter.next();
sb.append(key);
sb.append("=");
sb.append(param.get(key));
if (iter.hasNext()) {
sb.append("&");
}
}
return sb.toString();
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param req
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param timeout 连接超时时间 /单位毫秒
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map req,int timeout) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("content-type", "text/json");
conn.setRequestProperty("method","POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(timeout);//连接超时时间
// 获取URLConnection对象对应的输出流
StringBuilder sb=new StringBuilder();
Iterator<String> iterator = req.keySet().iterator();
while (iterator.hasNext()) {
String key=iterator.next().toString();
String val=req.get(key).toString();
sb.append(key);
sb.append("=");
sb.append(val);
if (iterator.hasNext()) {
sb.append("&");
}
} out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(sb);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),Charset.forName("utf-8")));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e+" url="+url+" param="+req+" time="+timeout);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param req 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String json) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("content-type", "text/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);//连接超时时间
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(json);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), Charset.forName("utf-8")));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e+" url="+url);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} public static void main(String[] args) {
// http://10.144.48.82/mobile_api/serviceApi?method=product.ProductService.getGoodsInfo&skuNo=8001019816 String re = new HttpUtils().sendGet("http://10.144.48.82/serviceApi",
"method=product.getGoodsInfo&skuNo=8001019816",60);
// System.out.println(re);
} public String post(String url, String encoding, Map<String,String> map){
boolean checkFlag = false; HttpPost post = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try { //String url = "http://localhost:8081/batchCates";//Constant.PERMISSION_URL; post = new HttpPost(url);
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
//LOG.info(entry.getValue());
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,encoding);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
//LOG.info(System.currentTimeMillis() - startTime);
HttpEntity resEntiy = response.getEntity();
String result = EntityUtils.toString(resEntiy);
return result; } catch (Exception e) {
e.printStackTrace();
} return ""; } }
Http请求get和post调用的更多相关文章
- 使用SpringAOP获取一次请求流经方法的调用次数和调用耗时
引语 作为工程师,不能仅仅满足于实现了现有的功能逻辑,还必须深入认识系统.一次请求,流经了哪些方法,执行了多少次DB操作,访问了多少次文件操作,调用多少次API操作,总共有多少次IO操作,多少CPU操 ...
- http异步请求的一种调用示例
在异步编程中,经常会调用已经写好的异步方法.这时会有一个需求:根据异步方法的返回值,做一些别的操作. 1.0 重新开启一个异步方法,在这个新的异步方法内部,调用需要请求的异步方法.示例: static ...
- java后台调用HttpURLConnection类模拟浏览器请求(一般用于接口调用)
项目开发中难免遇到外部接口的调用,小生今天初次接触该类,跟着API方法走了一遍,如有不对的地方,还请哆哆指正,拜谢! 1 package com.cplatform.movie.back.test; ...
- 原生js,jquery ajax请求以及jsonp的调用
ajax 是用来处理前后端交互的技术,可以改善用户体验,其本质是 XMLHttpRequest,异步访问服务器并发送请求数据,服务器返回响应的数据,以页面无刷新的效果改变页面中的局部内容 ...
- http请求,HttpClient,调用短信接口
项目中安全设置找回密码的功能,需要通过发送短信验证绑定手机,通过绑定的手机号验证并重新设置密码. 因为项目是通过maven管理的,所以需要在pom.xml文件中引入jar包, maven引入的jar包 ...
- 基于python实现GET和POST请求及token相关调用
GET请求实例: #coding:utf- import requests parm={"}#封装登录参数 r=requests.get("http://space.test.co ...
- 《React后台管理系统实战 :三》header组件:页面排版、天气请求接口及页面调用、时间格式化及使用定时器、退出函数
一.布局及排版 1.布局src/pages/admin/header/index.jsx import React,{Component} from 'react' import './header. ...
- 封装网络请求并在wxml调用
https://blog.csdn.net/qq_35713752/article/details/78109084 // url:网络请求的url method:网络请求方式 data:请求参数 m ...
- MOOC(7)- case依赖、读取json配置文件进行多个接口请求-测试类中调用封装的mock(10)
封装mock后,在单元测试中调用 # -*- coding: utf-8 -*- # @Time : 2020/2/11 8:35 # @File : test_class_10.py.py # @A ...
随机推荐
- 3509.com 纵横天下虚拟主机,垃圾中的战斗机
被纵横天下主机(3509.com)这间垃圾公司气疯了,他们公司自己要更换server(空间).居然把我挂在上面的站点数据弄丢了.并且更换连一封Email通知都没有.更离谱的是,跟他们反映这个情况后.他 ...
- JFinal项目搭建
1.Myeclipse中 新建 Dynamic Web Project 导入jar包 2.配置web.xml <?xml version="1.0" encoding=& ...
- linux环境配置时钟同步ntpd服务
配置: 服务器1:192.168.169.139 服务器2:192.168.169.140 服务器3:192.168.169.141 目的:NTP能与互联网的时间保持同步,而且本身也是一台NTP服务器 ...
- 重置Linux普通账号和root账号密码
今天想在Linux测试下HTTPie, 突然发现虚拟机里面的Linux, root账号和普通账号密码都忘记了. 百度了半天发现答案都不对, 最后用Google搜到了答案. 本人系统环境: VMware ...
- 超过两行显示省略号 -webkit-line-clamp、-webkit-box-orient vue打包后不起作用
为了实现两行显示缩略显示,但是本地是可以显示,打包后不起作用 word-break: break-all; text-overflow: ellipsis; display: -webkit-box; ...
- GIL解释器,协程,gevent模块
GIL解释器锁 在Cpython解释器中,同一个进程下开启的多线程,同一时刻只能有一个线程执行,无法利用多核优势 首先需要明确的一点是GIL并不是Python的特性,它是在实现Python解析器(CP ...
- SLF4J日志系统在项目导入时频现的问题
一.概述 近期在导入一个已有的项目时,日志系统出现了一个问题.错误信息如下: SLF4J问题 SLF4J: Failed to load class "org.slf4j.impl.Stat ...
- Unity,自带Random函数,上下限注意的地方
Random.Range() 该函数有两个重载,分别是 float和 int 的,这两者还是有差别的,具体是: float型,随机值涵盖: 最小和最大值 Random.Range(0f,1f) 是有可 ...
- CSS的单位 及 css3的calc() 及 line-height 百分比
CSS的单位及css3的calc()及line-height百分比 摘自:http://www.haorooms.com/post/css_unit_calc 单位介绍 说到css的单位,大家应该首先 ...
- 【Thinking in java, 4e】复用类
mark一篇09年的<Thinking in Java>笔记:here --> https://lawrence-zxc.github.io/2009/11/07/thinking- ...