运用场景说明
在平时做项目中不敢说经常,但是应该会遇到需要连接别人的接口获取数据的一些问题,特别是多个部门联合开发的时候,我平时也遇到了一些,而且有的感觉很有意思,所以本次记录下来!本次是一个util类可以直接用,话不多说,直接先上代码(注:本人是java开发,开发工具idea)
// An highlighted block
package com.server.common.util;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class GetPostUtil {
/**
* post请求
*/
public static String sendPost(String url, String param) {
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)");
// 发送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()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常:" + e);
e.printStackTrace();
}
//关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* GET方法
*/
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();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestMethod("GET");// 提交模式
// 设置请求属性
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
httpURLConnection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = httpURLConnection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// result +=key;
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常:" + e);
e.printStackTrace();
}
// 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 发送Put或者Delete方法的请求
*/
public static String sendDelete(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 链接URL
HttpURLConnection connection = (HttpURLConnection) 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.setRequestMethod("DELETE");
// connection.setRequestProperty("timestamp", timestamp);
// connection.setRequestProperty("CompanyCode", CompanyCode);
// connection.setRequestProperty("companyPassword", companyPassword);
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
result += key;
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送DELETE请求出现异常:" + e);
e.printStackTrace();
}
// 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* post请求(header带参数)
*/
public static String sendPostHeader(String url, String param, String bearer) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 链接URL
URLConnection conn = realUrl.openConnection();
// 设置请求属性
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + bearer);//带的header参数
conn.setRequestProperty("connection", "Keep-Alive");
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()));
ing line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
}
}
}
return result;
}
}
post介绍
其中sendGet,sendPost,sendDelete三个接口都是正常的http接口。main测试如下:
public static void main(String[] args) {
String path="http://127.1.1.1:8080/queryConfigResource";//链接的接口路径
System.out.println(path);
String sss1 = GetPostUtil.sendPost(path, "orderId=1111201&workOrderId=1019"); //post参数用"="号表示,多个参数用"&"进行分割
System.out.println(sss1);
}
关于sendPostHeader
有时候会遇到一些其他的接口,比如会在post里边加入headers,对方接口信息如下
//接口详情
$response = $client->request('POST', 'http://127.0.0.1/resConfResponse', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token,
],
'form_params' => [
'project_id' => '1',
],
]);
上边是对方给的接口信息,其中参数中带了headers和form_params两种,其中headers中指定了accept的格式,以及header带的参数Authorization,对应的Bearer 中的token,我直接写在了sendPostHeader接口内部(只是简单的加了一行),然后一样的带参数访问就好了。当然自己也可以根据遇到的对应的接口信息进行修改。
有一次遇到了raw格式的接口,以上的接口信息就不太适合了,然后自己单独写了一个方法类,有到的方法点过时了,但是还是记录一下吧
/**
* 获取接口数据
*/
public static String resConfigResponse(String url, String json) {
HttpClient httpClient = new DefaultHttpClient();//该方法会提示过时
// HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity postingString = null;// json传递
String content = null;
try {
postingString = new StringEntity(json);
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
org.apache.http.HttpResponse response = httpClient.execute(post);
content = EntityUtils.toString(response.getEntity());
System.out.println(content);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
注:1. HttpClient httpClient = new DefaultHttpClient();//该方法会提示过时
2. HttpClient client = HttpClientBuilder.create().build();//获取DefaultHttpClient请求
** 1 方法为我用的方法,会提示过时,可以用 2 方法代替
以上为我个人愚见,若有不对的地方,请给与指正,万分感谢!