两种方法:
一种是httpclient
一种是httpurlconnection
package com.networkbench.newlens.alarm.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.ssh2.crypto.Base64;
import com.alibaba.fastjson.JSONObject;
import com.google.common.net.MediaType;
/**
* 用于调用ows接口
* @author Administrator
*
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
*发送post请求
*/
public static void post(JSONObject jsonObject,String method){
// String url = "http://localhost:8080/tingyun-qy-report-server/apm/alarm/synchronize/list?start=0&limit=10"
// + "&orderBy=null&asc=true";
String url = "";
if(ZQZT.loadProperties("conf.local/conf-deploy.properties")){
url = ZQZT.getParam("newlens.alarm.owsservice_url");
}else{
logger.info("读取配置文件失败");
}
if(!StringUtils.isBlank(url)){
if(method.equals("insert")){
url=url+"v1/ai_alarm_status";
method="POST";
}else {
url=url+"rest/alarm-receive/v1/alarm-receive-services ";
method="PUT";
}
try {
//创建链接
HttpURLConnection connection = getConnection(url,method);
OutputStream outputStream = connection.getOutputStream();
//发送数据
//String param = "name=nb&password=TingYun@2016";
outputStream.write(jsonObject.toString().getBytes());
outputStream.flush();
outputStream.close();
//判断响应码
if (connection.getResponseCode() != 200) {
logger.info("http链接失败。。。。");
}
dealWithResp(connection);
//释放链接
connection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.info("" + e.getMessage());
}
}else {
logger.error("获取 url 地址 为空!!!!!");
}
}
/**
* 创建HttpURLConnection链接
* @param url
* @return
*/
public static HttpURLConnection getConnection(String url,String method){
try {
URL url2 = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url2.openConnection();
//打开可以向服务器发送消息
httpURLConnection.setDoOutput(true);
//设置请求方式
httpURLConnection.setRequestMethod(method);
//设置请求头
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("Server", "example-server");
httpURLConnection.setRequestProperty("Authorization", "Basic YXBtX3N5c3RlbTpQYXNzd29yZC4xMjM0NTY=");
return httpURLConnection;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.info("创建httpUrlConnection 失败 : " + e.getMessage());
}
return null;
}
/**
* 处理响应数据
* @param connection
*/
public static void dealWithResp(HttpURLConnection connection){
//获取相应数据
try {
String line = null;
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((connection.getInputStream())));
while ((line = responseBuffer.readLine()) != null) {
logger.info("########################## : "+line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.info("获取响应数据错误 : " + e.getMessage());
}
}
public static void testHttpClient(){
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
httpPost.setHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization","Basic dGluZ3l1bnRlc3QwOTExOkh1YXdlaUAxMjM0NQ==");
JSONObject jsonParam = new JSONObject();
jsonParam.put("User Name", "apm_system");
jsonParam.put("Password", "Password.123456");
String result="";
try {
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,"utf-8");
}
}
//获取响应码
int statusCode = response.getStatusLine().getStatusCode();
logger.info("result : "+result);
logger.info("result statusCode : " + statusCode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// private String getFromBASE64(String s) {
// Base64.encode((username + ":" + password).getBytes());
// }
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("start", 0);
jsonObject.put("limit", 1);
jsonObject.put("orderBy", "firstoccurrence");
jsonObject.put("asc", true);
char[] encode = Base64.encode(("tingyuntest0911" + ":" + "Huawei@12345").getBytes());
System.out.println(encode);
// post(jsonObject,"insert");
// testHttpClient();
// String url = "http://localhost:8080/tingyun-qy-report-server/apm/alarm/synchronize/list?start=0&limit=10";
// HttpURLConnection connection = getConnection(url);
// dealWithResp(connection);
}
}
注:下面的代码是抄袭别人的。哈哈。。。
问题:在微服务框架之外的系统中,我们经常会遇到使用httpClient进行接口调用的问题,除了进行白名单的设置,很多时候我们需要在接口调用的时候需要身份认证。翻了一下官方文档,解决方法很多,但是都不太符合实际业务场景,这里提供一种简单粗暴的解决方法。
解决方法:利用请求头,将验证信息保存起来。
public class HttpClientUtils {
protected static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
private static final String AUTHENKEY = "Authorization";
private static final String BASICKEY = "Basic ";
public static String getConnect(String url,String username,String password) {
CloseableHttpResponse response = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
Base64 token = new Base64();
String authenticationEncoding = token.encodeAsString(new String(username + ":" + password).getBytes());
httpGet.setHeader(AUTHENKEY, BASICKEY + authenticationEncoding);
String responseContent = "";
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
LOG.error(e.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOG.error(e.toString());
}
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
LOG.error(e.toString());
}
}
}
return responseContent;
}
}