使用场景:
在微信,QQ等第三方对接的时候使用,记录一下
方法一:
引入http-request包
<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>5.6</version>
</dependency>
示例发送get请求
/**
* 发送qqGET请求
* @param url 请求url
* @return map结果集
*/
public String get(String url){
String jsonResp = doGet(url);
logger.info("[weixin]: do get request({}), and get response({}).", url, jsonResp);
return jsonResp;
}
private String doGet(String url){
String jsonResp = HttpRequest.get(url).body();
// String jsonResp = HttpRequest.post(url).body();//POST请求
return jsonResp;
}
方法二:
//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往服务器端写内容 也就是发起http请求需要带的参数
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
logger.info("[weixin]: do get request({}), and get response({}).", url, buffer.toString());
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}