调用http接口
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
public class HttpURL {
public static String httpURLConnection(String strPostURL, Map<String, String> map, String contentType, String method) {
contentType = contentType != null && contentType.length() > 0 ? contentType : "application/x-www-form-urlencoded";
try {
method = method != null ? method : "POST";
URL url = new URL(strPostURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method.toUpperCase());
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-Type", contentType + ";charset=utf-8");
connection.setRequestProperty("charset", "utf-8");
StringBuilder sb = new StringBuilder();
if (map != null && map.size() > 0) {
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
if (sb.length() == 0) {
sb.append(key + "=" + URLEncoder.encode((String) val, "utf-8"));
} else {
sb.append("&" + key + "=" + URLEncoder.encode((String) val, "utf-8"));
}
}
connection.setRequestProperty("Content-length", String.valueOf(sb.toString().length()));
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
printWriter.write(sb.toString());
printWriter.flush();
printWriter.close();
}
connection.connect();
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuilder result = new StringBuilder();
while ((line = bf.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));
}
bf.close();
connection.disconnect();
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return "httpURLConnection调用失败";
}
}
}