java发送http的get、post请求
java发送http的get、post请求
package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 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.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */
public static String sendPost(String url, String param) { try { URL httpurl = new URL(url); HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection(); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; " + "Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); httpConn.setConnectTimeout(8 * 1000); httpConn.setReadTimeout(10 * 1000); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); httpConn.connect(); OutputStream outputStream = httpConn.getOutputStream(); PrintWriter out = new PrintWriter(outputStream); out.print(param); out.flush(); out.close(); InputStream inputStream = httpConn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } String resp = stringBuffer.toString(); // System.out.println(resp); if (stringBuffer != null) { try { bufferedReader.close(); } catch (IOException var18) { var18.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException var17) { var17.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException var17) { var17.printStackTrace(); } } return resp; }catch (IOException e) { throw new RuntimeException(String.format("url:%s,param:%s,message:%s", url, param, e.getMessage()), e); }
public static String sendPostXml(String uri,String xml) { try { // 创建url资源 URL url = new URL(uri); // 建立http连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); //转换为字节数组 byte[] data = xml.getBytes(); // 设置文件长度 conn.setRequestProperty("Content-Length", String.valueOf(data.length)); // 设置文件类型: conn.setRequestProperty("contentType", "text/xml"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write(data); out.flush(); out.close(); System.out.println(conn.getResponseCode()); // 请求返回的状态 if (conn.getResponseCode() == 200) { System.out.println("连接成功"); // 请求返回的数据 InputStream in = conn.getInputStream(); String a = null; try { byte[] data1 = new byte[in.available()]; in.read(data1); // 转成字符串 a = new String(data1); return a; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { return conn.getResponseMessage(); } } catch (Exception e) { } return ""; }
}
调用方法:
public static void main(String[] args) { //发送 GET 请求 String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456"); System.out.println(s); //发送 POST 请求 String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456"); System.out.println(sr); }