java设置请求方式请求头(HttpPost和HttpURLConnection)

HttpPost:
	httpPost.addHeader("x-access-token",token);
public static String post(String strURL, String params, String token) {
        System.out.println(strURL);
        System.out.println(params);
        Map<String,Object> map = new HashMap<>();
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.addRequestProperty("x-access-token",token);
            // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            //一定要用BufferedReader 来接收响应, 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();
            return res;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return "请求错误"; // 自定义错误信息
    }
HttpURLConnection:
	connection.addRequestProperty("x-access-token",token);
 public static String sendRequest(String url, Map<String,Object> map,String token) {
        String result = "";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            // 创建一个提交数据的容器
            List<BasicNameValuePair> parames = new ArrayList<>();
            Set<String> keys = map.keySet();
            for(String key:keys){
                System.out.println("key值:"+key+" value值:"+map.get(key));
                parames.add(new BasicNameValuePair(key, (String) map.get(key)));
            }
            try {

                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
                httpPost.addHeader("x-access-token",token);
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中发送HTTP POST请求并设置报文头的expect参数,可以使用Java内置的HttpURLConnection类。以下是一个示例代码: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostWithExpectHeader { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String jsonBody = "{\"name\": \"John\", \"age\": 30}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置HTTP请求方法为POST con.setRequestMethod("POST"); // 设置报文头的expect参数 con.setRequestProperty("Expect", "100-continue"); // 设置请求体 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(jsonBody.getBytes()); os.flush(); os.close(); // 获取响应 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(); // 输出响应 System.out.println("Response Code : " + responseCode); System.out.println("Response Body : " + response.toString()); } } ``` 在代码中,我们首先建立一个URL对象,然后使用HttpURLConnection打开连接。我们设置HTTP请求方法为POST,并设置报文头的expect参数为"100-continue"。接下来,我们设置请求体并发送请求。最后,我们获取响应并输出响应码和响应体。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值