做一个简单的http请求
java中有事需要去用http做远程请求,获取参数:
这里举一个实际用到的简单http连接,请求参数为:param,返回参数为:fileName
public class HttpConnection {
@Value("${user.ip}")
private String ip;
@Value("${user.port}")
private Integer port;
public String getResult(String param){
String url = "http://"+ip+port+"app/planMng/qryAttachmentsById?factsId="+param;
String fileName = "";
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream inputStream=null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setReadTimeout(5000);
connection.setConnectTimeout(10000);
connection.setRequestProperty("accept","'/'");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;)");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int num = -1;
while ((num = inputStream.read(buffer)) !=-1){
byteArrayOutputStream.write(buffer,0,num);
}
byte[] bs = byteArrayOutputStream.toByteArray();
String string = new String(bs,"UTF-8");
System.out.println(string);
JSONObject parseObject = (JSONObject) JSONArray.parse(string);
JSONObject redata = parseObject.getJSONObject("retData");
JSONArray a = redata.getJSONArray("data");
JSONObject nameObject = (JSONObject) a.get(0);
fileName = nameObject.getString("name");
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
inputStream.close();
connection.disconnect();
}catch (Exception e){
e.printStackTrace();
}finally {
if(null != byteArrayOutputStream){
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileName;
}
}
简单实用
记得当年在银行做的一个直连请求,示例:
public class HttpCommonUtils {
private static final Log log = LogFactory.getLog(HttpCommonUtils.class);
private static final String CONSTANT_ENCODING = "UTF-8";
/**
* 发送HttpPost请求
*
* @param requestUrl 请求地址
* @param requestParam 请求参数
* @return 成功:返回json字符串<br/>
*/
public static String postRequest(String requestUrl, Map<String, Object> requestParam) {
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuffer result = new StringBuffer();
log.info("获取请求地址:" + requestUrl);
log.info("获取请求参数:" + requestParam);
try {
// Post请求的url,与get不同的是不需要带参数
URL url = new URL(requestUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//从连接读取数据,默认是true
connection.setDoInput(true);
/**
* 设置是否向connection输出,因为这个是post请求,参数要放在
*http正文内,因此需要设为true
**/
connection.setDoOutput(true);
// Post 请求不能使用缓存
connection.setUseCaches(false);
//设置本次连接是否自动重定向
connection.setInstanceFollowRedirects(true);
// 默认是 GET方式
connection.setRequestMethod("POST");
/**
* 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
* 意思是正文是urlencoded编码过的form参数
*/
connection.setRequestProperty("Accept-Charset", CONSTANT_ENCODING);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=" + CONSTANT_ENCODING);
/**
* 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
* 要注意的是connection.getOutputStream会隐含的进行connect
*/
connection.connect();
//设置数据发送格式
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), CONSTANT_ENCODING);
outputStreamWriter.write(JSONObject.toJSONString(requestParam));
outputStreamWriter.flush();
outputStreamWriter.close();
outputStreamWriter = null;
//获取返回
inputStream = connection.getInputStream();
//此处读取字节流
inputStreamReader = new InputStreamReader(inputStream, CONSTANT_ENCODING);
bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
while (null != (line = bufferedReader.readLine())) {
result.append(line);
}
log.info("接收到的返回参数:" + result);
inputStream.close();
inputStream = null;
inputStreamReader.close();
inputStreamReader = null;
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toString();
}
}