为了使用这个类,我们模拟来发送请求。
我们在京东万象中申请了一个免费的api接口,来模拟这个请求。
代码示例如下:
package cn.xiaomin.http;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import org.springframework.util.StreamUtils;
/**
* HttpURLConnection的用法
* 模拟http请求
* @author Administrator
*
*/
public class HttpTest {
public static void main(String[] args) throws Exception {
//定义需要访问的地址
URL url = new URL("https://way.jd.com/jisuapi/search");
//2.与服务器建立连接
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
//3.设置请求的方式
conn.setRequestMethod("POST");
//4.需要输出的参数,默认为false,不输出,我们让他输出
conn.setDoOutput(true);
//5.拼接参数信息
StringBuffer param = new StringBuffer();
param.append("keyword=").append("土豆");
param.append("&num=").append("1");
param.append("&appkey=").append("c57af9eadd710aaf6025bd64672e47c4");
//6.写出参数
conn.getOutputStream().write(param.toString().getBytes("UTF-8"));
//7.发起请求
conn.connect();
//8.接受对方响应的信息 StreamUtils是spring中的包
String str=StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8"));
System.out.println(str);
}
}
返回结果
{"code":"10000","charge":false,"msg":"查询成功","result":{"status":"0","msg":"ok","result":{"num":"1","list":[{"id":"2","classid":"2","name":"开心土豆泥","peoplenum":"3-4人","preparetime":"10分钟内","cookingtime":"30分钟-1小时","content":"粉粉绵绵的土豆泥,加入玉米粒、青豆点缀,色彩亮丽清新,而火腿肠更是增加了口感,造型圆圆的,十分的可爱哦!","pic":"http://api.jisuapi.com/recipe/upload/20160719/115137_58878.jpg","tag":"下午茶,减肥,家常菜,春季,甜,甜品,私房菜,素菜,蒸","material":[{"mname":"火腿肠","type":"0","amount":"50g"},{"mname":"玉米粒","type":"0","amount":"30g"},{"mname":"青豆","type":"0","amount":"30g"},{"mname":"沙拉酱","type":"0","amount":"适量"},{"mname":"牛奶","type":"0","amount":"少许"},{"mname":"盐","type":"0","amount":"1勺"},{"mname":"土豆","type":"1","amount":"2个"}],"process":[{"pcontent":"首先将去皮土豆切成块,泡入清水,火腿肠切粒。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162542_28654.jpg"},{"pcontent":"将土豆放入蒸锅,隔水蒸十分钟,取出。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162542_65552.jpg"},{"pcontent":"将玉米粒、青豆,放入蒸锅,隔水蒸十分钟,取出。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162543_51629.jpg"},{"pcontent":"将土豆压成泥,放入火腿、青豆、玉米粒,挤入适量沙拉酱,再淋入少量牛奶,放入半勺盐,搅拌均匀,用模具压成心形,就可以享用了。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162543_43692.jpg"}]}]}}}
为了以后方便的使用,我把这个封装了成一个工具类
package cn.xiaomin.http;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.util.StreamUtils;
public class HttpUtil {
/**
* 模拟浏览器的请求
* @param httpURL 发送请求的地址
* @param params 请求参数
* @return
* @throws Exception
*/
public static String sendHttpRequest(String httpURL,Map<String,String> params) throws Exception{
//建立URL连接对象
URL url = new URL(httpURL);
//创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求的方式(需要是大写的)
conn.setRequestMethod("POST");
//设置需要输出
conn.setDoOutput(true);
//判断是否有参数.
if(params!=null&¶ms.size()>0){
StringBuilder sb = new StringBuilder();
for(Entry<String,String> entry:params.entrySet()){
sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
//sb.substring(1)去除最前面的&
conn.getOutputStream().write(sb.substring(1).toString().getBytes("utf-8"));
}
//发送请求到服务器
conn.connect();
//获取远程响应的内容.
String responseContent = StreamUtils.copyToString(conn.getInputStream(),Charset.forName("utf-8"));
conn.disconnect();
return responseContent;
}
/**
* 模拟浏览器的请求
* @param httpURL 发送请求的地址
* @param jesssionId 会话Id
* @return
* @throws Exception
*/
public static void sendHttpRequest(String httpURL,String jesssionId) throws Exception{
//建立URL连接对象
URL url = new URL(httpURL);
//创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求的方式(需要是大写的)
conn.setRequestMethod("POST");
//设置需要输出
conn.setDoOutput(true);
conn.addRequestProperty("Cookie","JSESSIONID="+jesssionId);
//发送请求到服务器
conn.connect();
conn.getInputStream();
conn.disconnect();
}
}
工具类的用法
package cn.xiaomin.http;
import java.util.HashMap;
import java.util.Map;
public class HttpTest2 {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("keyword", "梅菜扣肉");
map.put("num", "1");
map.put("appkey", "c57af9eadd710aaf6025bd64672e47c4");
String str=HttpUtil.sendHttpRequest("https://way.jd.com/jisuapi/search", map);
System.out.println(str);
}
}
返回结果:
{"code":"10000","charge":false,"msg":"查询成功","result":{"status":"0","msg":"ok","result":{"num":"1","list":[{"id":"2","classid":"2","name":"开心土豆泥","peoplenum":"3-4人","preparetime":"10分钟内","cookingtime":"30分钟-1小时","content":"粉粉绵绵的土豆泥,加入玉米粒、青豆点缀,色彩亮丽清新,而火腿肠更是增加了口感,造型圆圆的,十分的可爱哦!","pic":"http://api.jisuapi.com/recipe/upload/20160719/115137_58878.jpg","tag":"下午茶,减肥,家常菜,春季,甜,甜品,私房菜,素菜,蒸","material":[{"mname":"火腿肠","type":"0","amount":"50g"},{"mname":"玉米粒","type":"0","amount":"30g"},{"mname":"青豆","type":"0","amount":"30g"},{"mname":"沙拉酱","type":"0","amount":"适量"},{"mname":"牛奶","type":"0","amount":"少许"},{"mname":"盐","type":"0","amount":"1勺"},{"mname":"土豆","type":"1","amount":"2个"}],"process":[{"pcontent":"首先将去皮土豆切成块,泡入清水,火腿肠切粒。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162542_28654.jpg"},{"pcontent":"将土豆放入蒸锅,隔水蒸十分钟,取出。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162542_65552.jpg"},{"pcontent":"将玉米粒、青豆,放入蒸锅,隔水蒸十分钟,取出。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162543_51629.jpg"},{"pcontent":"将土豆压成泥,放入火腿、青豆、玉米粒,挤入适量沙拉酱,再淋入少量牛奶,放入半勺盐,搅拌均匀,用模具压成心形,就可以享用了。","pic":"http://api.jisuapi.com/recipe/upload/20160719/162543_43692.jpg"}]}]}}}