发送http请求 Java.net
程序员文章站
2024-02-26 09:00:46
...
发送http请求的例子
package com.jrt.common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; public class Http { public static String post(String url, String param) throws IOException { URL reqUrl = new URL(url); final HttpURLConnection connection = (HttpURLConnection) reqUrl .openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setConnectTimeout(300 * 1000); connection.setReadTimeout(300 * 1000); OutputStreamWriter reqOut = null; if (param != null) { reqOut = new OutputStreamWriter(connection.getOutputStream()); reqOut.write(param); reqOut.flush(); } int charCount = -1; InputStream in = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "GBK")); StringBuffer responseMessage = new StringBuffer(); while ((charCount = br.read()) != -1) { responseMessage.append((char) charCount); } in.close(); if (reqOut != null) reqOut.close(); return responseMessage.toString(); } }