如何使用java模拟post请求

2025-05-14 15:40:47
推荐回答(2个)
回答(1):

/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

回答(2):

两种选择:一、使用httpclient,二使用java自带的类库。
1、java自带类库:

public static String call(String address,String params) {

URL url = null;

HttpURLConnection httpurlconnection = null;

StringBuilder result = new StringBuilder();

try {

url = new URL(address);

// 以post方式请求

httpurlconnection = (HttpURLConnection) url.openConnection();

httpurlconnection.setDoOutput(true);

httpurlconnection.setRequestMethod("POST");

if(null!=params&¶ms.length()>0){

httpurlconnection.getOutputStream().write(params.getBytes());

httpurlconnection.getOutputStream().flush();

httpurlconnection.getOutputStream().close();

}

// 获取页面内容

java.io.InputStream in = httpurlconnection.getInputStream();

java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, Config.DEFAULT_CHARSET));

String str = breader.readLine();

while (str != null) {

result.append(str);

str = breader.readLine();

}

breader.close();

in.close();

} catch (Exception e) {

} finally {

if (httpurlconnection != null)

httpurlconnection.disconnect();

}

return result.toString().trim();

}

2、httpclient:

public static String post(String url,String params){
HttpClient httpClient = new DefaultHttpClient();

StringBuilder builder = new StringBuilder();

HttpPost post = new HttpPost(url);

try {

if(null!=params){

post.setEntity(new StringEntity(params,"UTF-8"));

}

HttpResponse resp = httpClient.execute(post);

int statusCode = resp.getStatusLine().getStatusCode();

if(statusCode<=304){

HttpEntity entity = resp.getEntity();

if (entity == null) {

throw new IllegalArgumentException("HTTP entity may not be null");

}

if (entity.getContentLength() > Integer.MAX_VALUE) {

throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");

}

int i = (int)entity.getContentLength();

i = i<0 ? 4096 : i;

final InputStream instream = entity.getContent();

final Reader reader = new InputStreamReader(instream, Config.DEFAULT_CHARSET);

final CharArrayBuffer buffer = new CharArrayBuffer(i);

final char[] tmp = new char[1024];

int l;

while((l = reader.read(tmp)) != -1) {

buffer.append(tmp, 0, l);

}

builder.append(buffer);

}

post.abort();

} catch (Exception e) {

post.abort();

}

return builder.toString().trim();

}