一、简要记录HTTP请求过程
/**
* 发送http请求
* @param params 请求参数map
* @param queryUrl 请求url地址
* @param queryMethod 方法类型"POST"或者"GET"
* @return
*/
public static String sendHttp(Map<String, String> params,String queryUrl,String queryMethod)throws Exception {
HttpClient client = new HttpClient();
StringBuilder sb = new StringBuilder();
InputStream ins = null;
String param =getRequestJson(params);//querParam;
HttpMethodBase method=null;
if("POST".equals(queryMethod.toUpperCase())){
method = new PostMethod(queryUrl);
}else{
method = new GetMethod(queryUrl);
}
try {
method.setQueryString(param);
int statusCode = client.executeMethod(method);
logger.info("返回状态码:"+statusCode);
if (statusCode == HttpStatus.SC_OK) {
ins = method.getResponseBodyAsStream();
byte[] b = new byte[1024];
int r_len = 0;
while ((r_len = ins.read(b)) > 0) {
sb.append(new String(b, 0, r_len, method.getResponseCharSet()));
}
logger.info(sb.toString());
} else {
System.err.println("Response Code: " + statusCode);
}
} catch (IOException e) {
logger.error("Fatal transport error: " + e.getMessage());
} catch (Exception e){
logger.error("Fatal protocol violation: " + e.getMessage());
}
finally {
method.releaseConnection();
if (ins != null) {
ins.close();
}
logger.info("地址:"+queryUrl);
logger.info("-------发送参数-------");
for(String key : params.keySet()){
logger.info(key + ":" + params.get(key));
}
System.out.println("返回结果:"+sb.toString());
}
String s = sb.toString();
return s;
}
/**
* 将map格式拼装成json
* @param parameters
* @return
*/
public static String getRequestJson(Map<String,String> parameters) {
StringBuffer sb = null;
try {
sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(v!=null&&!v.equals("")){
v=URLEncoder.encode(v,"UTF-8");
}
sb.append(k+"="+v+"&");
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString().substring(0,sb.lastIndexOf("&"));
}
二、简单调用
public static void main(String[] args) {
try {
Map<String,String> map = new HashMap<String, String>();
map.put("uid", "001");
String result = sendHttp(map,"http://xxxxxxxx","POST");
logger.info("返回参数:"+rresult);
} catch (Exception e) {
e.printStackTrace();
}
}