Java后端发送get和post请求

采用restTemplate直接发送:

Get请求

示例:Integer shopNumber = restTemplate.getForObject(requestUrl,Integer.class,shopIds);

  • requestUrl:请求的url地址
  • Integer.class:返回值类型
  • shopIds:传入的内容,这里shopIds为一个List<String>类型的集合

Post请求

示例:Integer shopNumber = restTemplate.postForObject(requestUrl,shopIds,Integer.class);

Post请求和Get请求就是把返回值类型和传入的内容对换一下。

具体一点的内容可以参照:https://blog.csdn.net/u012702547/article/details/77917939或者

https://blog.csdn.net/itguangit/article/details/78825505

 

但是用restTemplate方式发送post请求携带json格式的数据时貌似会有一点问题,具体我也没有去了解,但是可以采用以下方式去替代。该代码有验证过,可以直接使用。

CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(requestUrl);
JSONObject response = null;
log.debug("requestUrl为" + requestUrl);
Integer shopNumber = 0;
try {
    StringEntity s = new StringEntity(JSONObject.toJSONString(shopIds));
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");//发送json数据需要设置contentType
    post.setEntity(s);
    HttpResponse res = httpclient.execute(post);
    log.debug("发送post请求");
    if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        log.info("post请求成功");
        String result = EntityUtils.toString(res.getEntity());// 返回json格式:
        log.info("number请求返回的数据为" + result);
        System.out.println(result);
        response = JSONObject.parseObject(result);
        shopNumber = (Integer) response.get("data");
        //如果需要返回一个类,可以用下面的方式去转换jason格式的数据
        //JSONArray data = (JSONArray) response.get("data");
        //cameraShops = JSONArray.parseArray(data + "", CameraShop.class);
    }
} catch (Exception e) {
    log.info(e.getMessage());
    return RestResultGenerator.createFailResult("获取摄像头门店数量错误");
}

 

新增:java发送post请求,使用multipart/form-data的方式传递参数,使用的HTTP框架是HttpURLConnection。网址也可参考:https://www.cnblogs.com/jying/p/10310865.html

post方法如下:

 private final static int CONNECT_TIME_OUT = 30000;
 private final static int READ_OUT_TIME = 50000;
 private static String boundaryString = getBoundary();

private byte[] post(String url, HashMap<String, String> map,HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }

 private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }

 

可以使用 Java 的 HttpUrlConnection 类来发送 POST 请求,然后从响应中获取 token。接着,可以使用该 token 发送 GET 请求,获取其他数据。以下是示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; public class Main { public static void main(String[] args) throws Exception { // 发送 POST 请求,获取 token String token = getToken(); // 使用 token 发送 GET 请求,获取其他数据 String data = getData(token); System.out.println(data); } private static String getToken() throws Exception { String url = "https://example.com/token"; String username = "username"; String password = "password"; // 构造 POST 请求 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Authorization", "Basic " + getAuthHeader(username, password)); con.setDoOutput(true); // 发送 POST 请求 String postParams = "grant_type=client_credentials"; con.getOutputStream().write(postParams.getBytes("UTF-8")); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 解析响应,获取 token String token = response.toString().split("\"")[3]; return token; } private static String getData(String token) throws Exception { String url = "https://example.com/data"; // 构造 GET 请求 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization", "Bearer " + token); // 发送 GET 请求 int responseCode = con.getResponseCode(); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 返回响应 return response.toString(); } private static String getAuthHeader(String username, String password) { String auth = username + ":" + password; byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes()); return new String(encodedAuth); } } ``` 其中,`getToken()` 方法发送 POST 请求,获取 token;`getData()` 方法使用 token 发送 GET 请求,获取数据。`getAuthHeader()` 方法用于构造 Authorization 头部,包含用户名和密码。注意,这里使用了 Base64 编码,因此需要导入 `java.util.Base64` 包。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值