最近在公司需要在第三方服务器上获取一些数据,可是公司和其他公司没有合作关系,只能通过发送跨域请求来获取了。通过整理,将其写成一个API接口,需要传入四个参数
1、reqType:请求方式,post和get请求
2、reqHeaders:请求头的设置,因为在做的时候会对请求头有一定的设置
3、reqParam:请求参数(post)
4、reqUrl:请求地址
下面就是我写的方法
使用的API有
URL:匹配连接
URLconnecti : 建立连接
注意点:
1、在发送post请求时,需要将URLconnection的setDoinput和setDooutput设置为true;
2、URLconnection的connect()方法其实在进行输出流时就隐试的调用了
代码
package cn.saleNc.uitl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
public class urlConnect {
/**
*
* @param requrl 请求地址
* @param reqparam 请求参数
* @param reqHeaders 请求头
* @param reqType 请求方式
* @return
*/
public static String reqGet(String requrl, String reqparam, String reqHeaders, String reqType ){
String result = "";
BufferedReader in = null;
PrintWriter out = null;
//真实的请求地址
String realUrl = "";
//判断是哪种请求方式(默认以get请求方式)
if ( "post" == reqType ){
realUrl = requrl;
try {
URL url = new URL(realUrl);
//打开URL连接
URLConnection urlCon = url.openConnection();
//设置请求头(判断请求头是否有设置的必要)
if ( reqHeaders.isEmpty() ){
String reqHeadersParam = reqHeaders.substring(1,reqHeaders.length());
String[] paramArr = reqHeadersParam.split(",");
String[] keyValue;
for (int n=0;n<paramArr.length;n++){
keyValue = paramArr[n].split(":");
urlCon.setRequestProperty(keyValue[0],keyValue[1]);
}
}
//设置下面两行才能发送post请求(因为post需要在URL通道中发送数据)
urlCon.setDoInput(true);
urlCon.setDoOutput(true);
//获取输出流
out = new PrintWriter(urlCon.getOutputStream());
//fluse输出流
out.flush();
//获取服务器的输入流
in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String param;
while ( (param = in.readLine()) != null ){
result += param;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
out.close();
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
try {
realUrl = realUrl + "?" + reqparam;
URL url = new URL(realUrl);
// 打开和URL之间的连接
URLConnection connection = url.openConnection();
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String param;
while ((param = in.readLine()) != null) {
result += param;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return result;
}
}