java发起HTTP 请求的多种方式

java发起HTTP 请求的多种方式,常用的类为 cn.hutool.http.HttpUtil

但方式有限,需加工,可根据实际情况进行选择

参数多为json格式字符串,先讲几个对象或者转json字符串的方式

1.对象转json串  

String data = JSONObject.toJSONString(bo);

2.拼接json字符串

String data = JSONObject.toJSONString(new HashMap<Object, Object>(1) {{                                            put("param1", new String[]{"123123"});

                     put("param2",1231);

                     put("param3","dss");

                     put("param4","asdad");

}});

String data = JSONObject.toJSONString(new HashMap<Object, Object>(3) {{

                    put("name", "zhang****");

                    put("user_id", "1101238723826918");

                    put("cards", new JSONObject(new HashMap<String, Object>(2) {{

                                                   put("type", "ID");

                                                   put("id", "32428269134582");

                                         }}

                          ).toJSONString());

}});

开始请求,以cn.hutool.http.*为例

1.post请求,参数1为请求路径,参数2默认为json格式字符串
String result = HttpUtil.post("url","data");

2.get请求,参数为url,可选多参数,设置参数或超时时间等
String result = HttpUtil.get("url");

3.添加请求头headers的的post请求

Map<String,String> headerMap = new HashMap<>();

headerMap.put("Content-Type","application/json");

...............

String result=HttpRequest.post("url").addHeaders(headerMap).body(data).execute().body();

4.delete  put请求为封装的工具类,如下

package ;

import com.aliyun.oss.common.comm.HttpDeleteWithBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @author 
 * @title: HttpClientUtil 处理cn.hutool.http.HttpUtil post get外的其他请求方式  delete put 等
 * @description: TODO
 * @date 
 */
public class HttpClientUtil {

    /**
     * 功能描述: delete
     *
     * @Param: [data, url]
     * @Return: java.lang.String
     */
    public static String doDelete(String url, String data) throws IOException {
        CloseableHttpClient client = null;
        HttpDeleteWithBody httpDelete = null;
        String result = null;
        try {
            client = HttpClients.createDefault();
            httpDelete = new HttpDeleteWithBody(url);

            httpDelete.addHeader("Content-type", "application/json; charset=utf-8");
            httpDelete.setHeader("Accept", "application/json; charset=utf-8");
            httpDelete.setEntity(new StringEntity(data));

            CloseableHttpResponse response = client.execute(httpDelete);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
        } finally {
            client.close();
        }
        return result;
    }


    public static String doPut(String urlPath, String data, String charSet, String[] header) {
        String result = null;
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        try {
            url = new URL(urlPath);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setConnectTimeout(5000);// 设置连接主机超时(单位:毫秒)
            httpurlconnection.setReadTimeout(5000);// 设置从主机读取数据超时(单位:毫秒)

            if (header != null) {
                for (int i = 0; i < header.length; i++) {
                    String[] content = header[i].split(":");
                    httpurlconnection.setRequestProperty(content[0], content[1]);
                }
            }

            httpurlconnection.setRequestMethod("PUT");
            httpurlconnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            if (StringUtils.isNotBlank(data)) {
                httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));
            }
            httpurlconnection.getOutputStream().flush();
            httpurlconnection.getOutputStream().close();
            int code = httpurlconnection.getResponseCode();

            if (code == 200) {
                DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                if (StringUtils.isNotBlank(charSet)) {
                    result = new String(by, Charset.forName(charSet));
                } else {
                    result = new String(by);
                }
                in.close();
            } else {
                System.out.println("请求地址:" + urlPath + "返回状态异常,异常号为:" + code);
            }
        } catch (Exception e) {
            System.out.println("访问url地址:" + urlPath + "发生异常");
        } finally {
            url = null;
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return result;
    }

}

 

Java中,发起API请求通常是指通过HTTP协议与服务器进行数据交互。以表单形式发起API请求,通常是指使用HTTP的POST方法来提交表单数据。以下是使用Java发起表单形式API请求的几种常见方法: 1. 使用`HttpURLConnection`类: 这是Java标准库提供的一个用于处理HTTP请求的类。可以通过创建一个`HttpURLConnection`实例,设置请求方法为"POST",并通过输出流写入表单数据来发起请求。 ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); Writer writer = new OutputStreamWriter(os, "UTF-8"); writer.write("param1=value1&param2=value2"); writer.flush(); writer.close(); os.close(); // 读取响应 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String responseLine = null; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } br.close(); System.out.println(response.toString()); ``` 2. 使用Apache HttpClient库: Apache HttpClient是一个功能强大的HTTP客户端库,支持多种HTTP请求方式,包括以表单形式提交数据。 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api"); List<NameValuePair> formParams = new ArrayList<>(); formParams.add(new BasicNameValuePair("param1", "value1")); formParams.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(formParams)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); ``` 3. 使用OkHttp库: OkHttp是一个处理HTTP请求的客户端库,简洁高效,支持同步和异步请求。 ```java OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("param1", "value1") .add("param2", "value2") .build(); Request request = new Request.Builder() .url("http://example.com/api") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { System.out.println(response.body().string()); } ``` 4. 使用Java内置的`javax.servlet.http.Part`和`javax.servlet.http.HttpServletRequest`类: 这种方法适用于在Java Web应用中处理表单数据。 ```java // 假设在servlet中处理请求 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Part part = req.getPart("file"); // 获取文件类型的表单字段 String formData = req.getParameter("param1"); // 获取普通表单字段 // 处理表单数据... } ``` 请注意,实际开发中还需要处理异常情况、字符编码、内容类型等问题,并且可能需要配置额外的请求头信息,例如设置`Content-Type`为`application/x-www-form-urlencoded`来表明提交的是表单数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值