调用HTTP的方法有很多种,使用Java原生的HttpURLConnection可以,也可以使用HttpClient包
package util;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class APIHelper {
private static Logger log =Logger.getLogger(APIHelper.class);
private static Logger errorLog =Logger.getLogger("errorlog");
public static void main(String[] args)
{
InputStream is = APIHelper.class.getClassLoader().getResourceAsStream("config/log4j.properties");
PropertyConfigurator.configure(is);
String url0 ="http://nkweb-uat.huawei.com/pm/services/dc/excel";//http://login-beta.huawei.com/login
String method ="POST";
Map<String,String> params =new HashMap<>();
int[] responseCode =new int[1];
params.put("paramName1", "paramValue1");
params.put("paramName2", "paramValue2");
String[] url ="http://localhost.huawei.com:8090/something";
String res =request(url[i],method,params1,responseCode);
System.out.println(responseCode[0]);
System.out.println(res);
}
public static String getRequest(String address, Map<String,String> map, int[] responseCode)
{
log.info("Enter getRequest()");
if(!map.isEmpty())
{
address +="?";
for(Map.Entry<String, String> entry :map.entrySet())
{
if(!address.endsWith("?")) address +="&";
address += entry.getKey()+"="+entry.getValue();
}
}
System.out.println(address);
return request(address,"GET",map,responseCode);
}
public static String request(String address, String method, Map<String,String> map, int[] responseCode)
{
log.info("Enter request()");
StringBuffer response =null;
responseCode[0] =404;
if(!checkURL(address)) return null;
BufferedReader br =null;
HttpURLConnection con =null;
try{
URL url =new URL(address);
con =(HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);//超时时间3秒
con.setRequestProperty("Accept-Language", "en-US;q=1");
con.setRequestProperty("Content-Type", "application/json;utf-8");
con.setRequestMethod(method);
con.setDoOutput(true);
DataOutputStream dos =new DataOutputStream(con.getOutputStream());
//设置参数格式
String data =setFormat(map);
if(!data.trim().equals("")) dos.writeBytes(data);
dos.flush();
dos.close();
responseCode[0] =con.getResponseCode();
if(responseCode[0] <400)
{
br =new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
}else{
if(null!=con.getErrorStream())
br =new BufferedReader(new InputStreamReader(con.getErrorStream(),"UTF-8"));
}
String inputLine;
response =new StringBuffer();
while(null!=br&&(inputLine =br.readLine())!=null)
{
response.append(inputLine);
response.append("\n");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
errorLog.error(address+":"+e);
errorLog.error(e.getMessage(),e);
e.printStackTrace();
}finally{
try{
if(br!=null) br.close();
}catch(IOException e){
e.printStackTrace();
}
if(con!=null) con.disconnect();
}
if(response!=null) return response.toString();
else return "nothing";
}
public static String setFormat(Map<String,String> map)
{
if(map.isEmpty()) return "";
StringBuilder sb =new StringBuilder("{");
for(Map.Entry<String, String> entry :map.entrySet())
{
if(sb.length()>1) sb.append(",");
sb.append("\""+entry.getKey()+"\":\""+entry.getValue()+"\"");
}
sb.append("}");
return sb.toString();
}
public static boolean checkURL(String url)
{
if(url==null) return false;
String regex ="https?://.*";
return Pattern.matches(regex, url);
}
}