Java中用于发送HTTP请求的工具类

 HttpClientUtil是Java中用于发送HTTP请求的工具类,它是基于Apache HttpClient实现的。下面是一个示例代码:


import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.NameValuePair;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtil2 {
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应内容
     */
    public static String sendGet(String url) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url    请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendPost(String url, Map<String, String> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> nameValuePairList = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送带参数的GET请求
     *
     * @param url    请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendGetWithParams(String url, Map<String, String> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = uriBuilder.build();
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        // get 请求
        //  String getUrl = "https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json";
        // String result = sendGet(getUrl);
        // System.out.println("result = " + result);

        //Post 请求  baocuo
        // String postUrl = "http://localhost:8088/device/factmag/getInfo";
        // Map m = new HashMap();
        // m.put("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjNkNmI3ZTFjLTU0ZjgtNGE2NS1iMTY1LTE2NjczYzM1MWIxZiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.AyLfDdY9PjpWInEnaiDUBdJVpStEsP1oheWrxCdRcflzJSWPL2VMFFL2SngTO5S0jrI3uwQBWAsccCOG4hRygg");
        // m.put("facregCode","999999");
        // String s = sendPost(postUrl, m);
        //System.out.println("s = " + s);

       /*String sendGetWithParamsUrl = "http://localhost:9888/boxes2/getprojectinfo";
        Map m = new HashMap();
        m.put("mac","98CC4D111DDE");
        String s = sendGetWithParams(sendGetWithParamsUrl, m);
        System.out.println("s = " + s);*/
    }
}

上述示例代码中,sendGet方法用于发送GET请求,sendPost方法用于发送POST请求,sendGetWithParams方法用于发送带参数的GET请求。这些方法都使用了相同的HTTP客户端实例,在请求结束后关闭该实例以释放资源。

在使用HttpClientUtil时,需要将Apache HttpClient的相关依赖项添加到项目的构建路径下,例如:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在微信小程序Java 写授权登录的代码可以这样写: 1. 先调用 wx.login() 方法,获取到小程序的 code(一个临时登录凭证)。 2. 然后把 code 发送给你的服务器,你的服务器再通过 code 去获取用户信息。具体来说,服务器需要调用微信提供的接口,使用 code 换取用户信息(包括用户的唯一标识 openid 和 会话密钥 session_key)。 3. 在服务器端获取到用户信息之后,把用户信息存储在服务器端的数据库。 4. 最后调用 wx.setStorageSync() 方法,把用户信息存储在小程序端。 下面是一段代码示例,它展示了如何调用 wx.login() 方法: ``` wx.login({ success: function(res) { if (res.code) { // 发送 res.code 到后台换取 openId, sessionKey, unionId console.log(res.code) } else { console.log('登录失败!' + res.errMsg) } } }); ``` 需要注意的是,上面的代码的 success 回调函数是在小程序端执行的,因此你需要在服务器端提供一个接口,供小程序端调用,使用 code 换取用户信息。 如果你想了解更多关于微信小程序授权登 ### 回答2: 在微信开发者工具使用Java编写微信小程序授权登录的代码,可以使用微信开放平台的API实现。以下是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeChatMiniProgramAuth { // 小程序 AppID 和 AppSecret private static final String APPID = "YOUR_APPID"; private static final String APPSECRET = "YOUR_APPSECRET"; public static void main(String[] args) { // 获取登录凭证code String code = "YOUR_CODE"; // 构造获取access_token的URL String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code + "&grant_type=authorization_code"; try { // 发起HTTP请求 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 读取API返回的JSON数据 InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { response.append(line); } bufferedReader.close(); // 解析JSON数据 String accessToken = response.toString(); // 处理access_token等信息 // 对用户数据进行处理 // ... } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码,需要将YOUR_APPID和YOUR_APPSECRET替换为在微信开放平台上注册的小程序的实际AppID和AppSecret。另外,需要将YOUR_CODE替换为实际的登录凭证code。 代码使用了java.net包下的HttpURLConnection类进行HTTP请求。在实际开发,可以使用更为方便的第三方类库(如Apache HttpClient)来发送HTTP请求并处理返回的JSON数据。 该示例代码只演示了如何获取access_token以及如何处理用户数据,实际开发还需要根据业务需求进行其他相关操作。 ### 回答3: 在微信开发者工具Java写一段微信小程序授权登录的代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeChatMiniProgramAuth { // 定义小程序AppId和AppSecret private static final String APP_ID = "YourMiniProgramAppId"; private static final String APP_SECRET = "YourMiniProgramAppSecret"; // 定义获取access_token的URL private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET; // 定义获取session_key和openid的URL private static final String SESSION_KEY_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=%s&grant_type=authorization_code"; // 定义登录凭证校验的URL private static final String LOGIN_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s"; public static void main(String[] args) throws IOException { // 获取access_token String accessToken = getAccessToken(); System.out.println("Access Token: " + accessToken); // 使用登录凭证校验 String code = "YourLoginCode"; loginWithCode(code, accessToken); } // 获取access_token private static String getAccessToken() throws IOException { URL url = new URL(ACCESS_TOKEN_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } // 解析获取的JSON数据,获取access_token // 这里需要使用JSON解析库进行解析,这里假设已经获得了access_token return "your_access_token"; } // 使用登录凭证校验 private static void loginWithCode(String code, String accessToken) throws IOException { URL url = new URL(String.format(SESSION_KEY_URL, code)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } // 解析获取的JSON数据,获取session_key和openid // 这里需要使用JSON解析库进行解析,这里假设已经获得了session_key和openid String sessionKey = "your_session_key"; String openid = "your_openid"; // 进行后续的授权登录逻辑处理 // ..... } } ``` 请注意,这段代码的相关URL地址需要替换为真实的微信小程序开发者服务器地址。同时,还需要使用JSON解析库来解析获取到的JSON数据,实际开发可以使用各种Java的JSON解析库,如Gson、Jackson等。另外,该代码只实现了获取access_token和使用登录凭证校验的功能,具体的授权登录逻辑需要根据实际需求进行进一步编写。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值