用java实现模拟http请求的简单介绍

发布时间:2022-11-17

本文目录一览:

  1. 如何使用HttpClient包实现JAVA发起HTTP请求
  2. 怎样用JAVA实现模拟HTTP请求,得到服务器的响应时间等参数
  3. 怎样编写http请求的java程序
  4. 怎么用java模拟http请求

如何使用HttpClient包实现JAVA发起HTTP请求

public class HttpClientUtil {
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    public static String doGet(String url) {
        return doGet(url, null);
    }
    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine());
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
    public static String doPost(String url) {
        return doPost(url, null);
    }
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

怎样用JAVA实现模拟HTTP请求,得到服务器的响应时间等参数

import java.net.*;
public class HttpDemo{
    public static void main(String[] args)throws Exception{
        URL url = new URL("地址");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        //获取网页的源码
        BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
        String line = "";
        while((line=br.readLine())!=null){
            System.out.println(line);
        }
        br.close();
        //获取参数:
        String value = getRequestProperty("key");
    }
}

怎样编写http请求的java程序

目前web上的消息通讯方式主要有以下几种。轮询,长连接,websocket

  • 轮询:隔一段时间访问服务器,服务器不管有没有新消息都立刻返回。
  • 长连接:页面向服务器发出请求,由服务器决定什么时候返回。(如果有新消息则立刻返回,没有的话就保持连接,直到有新消息才返回)
  • websocket:类似JavaSocket,由Http请求模拟实现的socket。 要实现长连接的关键就是:由服务器端决定什么时候返回数据。比如在servlet中。
doGet(){
    Thread.sleep(30000);
    return
}

这就是一个长连接的例子,只是没有任何意义而已。你要做的就是在doGet中阻塞住,

while(!hasNewMsg){
    sleep(500)
}
return newMsg

当然你的ajax超时时间要设置长一点。如果可以的话,最好可以使用websocket。

怎么用java模拟http请求

/*
 * 得到返回的内容
 */
public static String getResult(String urlStr, String content) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

追问: 没注释吗? 追答:

/*
 * 得到返回的内容
 */
public static String getResult(String urlStr, String content) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();//新建连接实例
        connection.setDoOutput(true);//是否打开输出流 true|false
        connection.setDoInput(true);//是否打开输入流true|false
        connection.setRequestMethod("POST");//提交方法POST|GET
        connection.setUseCaches(false);//是否缓存true|false
        connection.connect();//打开连接端口
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());//打开输出流往对端服务器写数据
        out.writeBytes(content);//写数据,也就是提交你的表单 name=xxxpwd=xxx
        out.flush();//刷新
        out.close();//关闭输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));//往对端写完数据 对端服务器返回数据 ,以BufferedReader流来读取
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();//关闭连接
        }
    }
    return null;
}