接口调用方式最常见的就是webservice,post,get。今天我学习了一下发送post和get请求的方式:
话不多说,直接上代码,一个通用的方法:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.Iterator;
import java.util.List;
import java.util.Map;
public class UrlUtils {
private static final Logger log = LoggerFactory.getLogger(UrlUtils.class);
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
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("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
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()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param paramMap 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, ?> paramMap) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
String param = "";
Iterator<String> it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
上面的是通用的发送请求,但是有的访问需要登陆验证才可以访问,所以还要加上cookie才可以成功
package com.els.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Properties;
import com.alibaba.fastjson.JSONObject;
import com.els.common.SysProperties;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
/**
* @author 小白
*/
public class HttpPostRequestRaw {
// public static void main(String[] args) {
// String postData = "{\"data\":[{\"docno\":\"QX20177248\"},{\"docno\":\"QX20177202\"}]}";
// String postUrl = "http://srm.skyworth-qx.com:998/api/cwapi/changeVoucherStatus?voucherType=po";
// String ss = sendPostJsonType(postData,postUrl);
// System.out.println(ss);
// }
public static String sendPostJsonType(String postData, String postUrl) {
// 调用该方法返回的值
JSONObject jsbRetrun = new JSONObject();
BufferedReader in = null;
OutputStreamWriter out = null;
HttpURLConnection conn = null;
try {
// 发送POST请求
URL url = new URL(postUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", "" + postData.length());
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(postData);
out.flush();
// 获取响应状态
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("connect failed!");
return "";
}
// 获取响应内容体
String line;
StringBuilder result = new StringBuilder();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while ((line = in.readLine()) != null) {
result.append(line);
}
jsbRetrun.put("state", "S");
// {"state":"S","remark":"","returnData":{}}
jsbRetrun.put("remark", "接口数据交互请求成功");
jsbRetrun.put("returnData", result.toString());
return jsbRetrun.toJSONString();
} catch (IOException e) {
e.printStackTrace(System.out);
jsbRetrun.put("state", "E");
// {"state":"E","remark":"错误信息","returnData":{}}
jsbRetrun.put("remark", e.getMessage());
return jsbRetrun.toJSONString();
}finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
jsbRetrun.put("state", "E");
// {"state":"E","remark":"错误信息","returnData":{}}
jsbRetrun.put("remark", e.getMessage());
return jsbRetrun.toJSONString();
}
}
}
public static String connectToK3(CloseableHttpClient httpClient, String url, String requestData){
String result = null;
try {
//读取配置文件
Properties config = SysProperties.INSTANCE.getProperties("sysconfig.properties");
//仕瑞达登录接口
String loginUrl = config.getProperty("srd.post.loginIp");
//post请求
HttpPost httpPost = new HttpPost(loginUrl);
//用户名
String username = config.getProperty("srd.post.userName");
//密码
String password = config.getProperty("srd.post.password");
org.json.JSONObject json = new org.json.JSONObject();
json.put("username", username);
json.put("password", password);
String j = json.toString();
//json请求设置
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(j, Charset.forName("UTF-8")));
//请求登录接口
HttpResponse httpResponse = httpClient.execute(httpPost);
//获取cookie
org.apache.http.Header setCookie = httpResponse.getFirstHeader("Set-Cookie");
String cookie = setCookie + ";domain=47.106.70.53;Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
cookie = cookie.substring(12);
System.out.println(cookie);
//获取登录状态
StatusLine statusLine = httpResponse.getStatusLine();
int status = statusLine.getStatusCode();
//登陆成功之后
if (200 == status) {
//仕瑞达获取数据接口
String posturl = url;
HttpPost httpPost1 = new HttpPost(posturl);
//设置请求头
httpPost1.setHeader("Content-type", "application/json; charset=utf-8");
httpPost1.setHeader("Accept", "application/json");
httpPost1.setHeader("Cookies", cookie);
httpPost1.setEntity(new StringEntity(requestData, Charset.forName("UTF-8")));
//请求仕瑞达获取数据接口
HttpResponse httpResponsee = httpClient.execute(httpPost1);
result = EntityUtils.toString(httpResponsee.getEntity(), "utf-8");
}
}catch(Exception e){
e.printStackTrace();
}finally {
// 关闭连接,释放资源
httpClient.getConnectionManager().shutdown();
}
return result;
}
}