最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JAVA發(fā)送HTTP請(qǐng)求的多種方式詳細(xì)總結(jié)

 更新時(shí)間:2023年01月30日 16:15:57   作者:流云一號(hào)  
目前做項(xiàng)目中有一個(gè)需求是這樣的,需要通過(guò)Java發(fā)送url請(qǐng)求,查看該url是否有效,這時(shí)我們可以通過(guò)獲取狀態(tài)碼來(lái)判斷,下面這篇文章主要給大家介紹了關(guān)于JAVA發(fā)送HTTP請(qǐng)求的多種方式總結(jié)的相關(guān)資料,需要的朋友可以參考下

程序員日常工作中,發(fā)送http請(qǐng)求特別常見(jiàn)。本文以Java為例,總結(jié)發(fā)送http請(qǐng)求的多種方式。

1. HttpURLConnection

使用JDK原生提供的net,無(wú)需其他jar包,代碼如下:

import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
public class HttpTest1 {
 
    public static void main(String[] args) {
        HttpURLConnection con = null;
 
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
 
        try {
            URL url = new URL("http://10.30.10.151:8012/gateway.do");
            //得到連接對(duì)象
            con = (HttpURLConnection) url.openConnection();
            //設(shè)置請(qǐng)求類型
            con.setRequestMethod("POST");
            //設(shè)置Content-Type,此處根據(jù)實(shí)際情況確定
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //允許寫出
            con.setDoOutput(true);
            //允許讀入
            con.setDoInput(true);
            //不使用緩存
            con.setUseCaches(false);
            OutputStream os = con.getOutputStream();
            Map paraMap = new HashMap();
            paraMap.put("type", "wx");
            paraMap.put("mchid", "10101");
            //組裝入?yún)?
            os.write(("consumerAppId=test&serviceName=queryMerchantService&params=" + JSON.toJSONString(paraMap)).getBytes());
            //得到響應(yīng)碼
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到響應(yīng)流
                InputStream inputStream = con.getInputStream();
                //將響應(yīng)流轉(zhuǎn)換成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                System.out.println("result:" + resultBuffer.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. HttpClient

需要用到commons-httpclient-3.1.jar,maven依賴如下:

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

代碼如下:

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class HttpTest2 {
 
    public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://10.30.10.151:8012/gateway.do");
 
        postMethod.addRequestHeader("accept", "*/*");
        //設(shè)置Content-Type,此處根據(jù)實(shí)際情況確定
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //必須設(shè)置下面這個(gè)Header
        //添加請(qǐng)求參數(shù)
        Map paraMap = new HashMap();
        paraMap.put("type", "wx");
        paraMap.put("mchid", "10101");
        postMethod.addParameter("consumerAppId", "test");
        postMethod.addParameter("serviceName", "queryMerchantService");
        postMethod.addParameter("params", JSON.toJSONString(paraMap));
        String result = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                result = postMethod.getResponseBodyAsString();
                System.out.println("result:" + result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. CloseableHttpClient

需要用到httpclient-4.5.6.jar,maven依賴如下: 

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

代碼如下:

import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class HttpTest3 {
 
    public static void main(String[] args) {
        int timeout = 120000;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        HttpPost httpPost = null;
        List<NameValuePair> nvps = null;
        CloseableHttpResponse responses = null;// 命名沖突,換一個(gè)名字,response
        HttpEntity resEntity = null;
        String result;
        try {
            httpPost = new HttpPost("http://10.30.10.151:8012/gateway.do");
            httpPost.setConfig(defaultRequestConfig);
 
            Map paraMap = new HashMap();
            paraMap.put("type", "wx");
            paraMap.put("mchid", "10101");
            nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("consumerAppId", "test"));
            nvps.add(new BasicNameValuePair("serviceName", "queryMerchantService"));
            nvps.add(new BasicNameValuePair("params", JSON.toJSONString(paraMap)));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
 
            responses = httpClient.execute(httpPost);
            resEntity = responses.getEntity();
            result = EntityUtils.toString(resEntity, Consts.UTF_8);
            EntityUtils.consume(resEntity);
            System.out.println("result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                responses.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. okhttp

需要用到okhttp-3.10.0.jar,maven依賴如下:

<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>3.10.0</version>
</dependency>

代碼如下:

import com.alibaba.fastjson.JSON;
import okhttp3.*;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class HttpTest4 {
 
    public static void main(String[] args) throws IOException {
        String url = "http://10.30.10.151:8012/gateway.do";
        OkHttpClient client = new OkHttpClient();
        Map paraMap = new HashMap();
        paraMap.put("yybh", "1231231");
 
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("consumerAppId", "tst")
                .addFormDataPart("serviceName", "queryCipher")
                .addFormDataPart("params", JSON.toJSONString(paraMap))
                .build();
 
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = client
                .newCall(request)
                .execute();
        if (response.isSuccessful()) {
            System.out.println("result:" + response.body().string());
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
}

5. Socket

使用JDK原生提供的net,無(wú)需其他jar包

此處參考:https://www.cnblogs.com/hehongtao/p/5276425.html

代碼如下:

import com.alibaba.fastjson.JSON;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
public class HttpTest6 {
 
    private static String encoding = "utf-8";
 
    public static void main(String[] args) {
        try {
            Map paraMap = new HashMap();
            paraMap.put("yybh", "12312311");
            String data = URLEncoder.encode("consumerAppId", "utf-8") + "=" + URLEncoder.encode("test", "utf-8") + "&" +
                    URLEncoder.encode("serviceName", "utf-8") + "=" + URLEncoder.encode("queryCipher", "utf-8")
                    + "&" +
                    URLEncoder.encode("params", "utf-8") + "=" + URLEncoder.encode(JSON.toJSONString(paraMap), "utf-8");
            Socket s = new Socket("10.30.10.151", 8012);
            OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append("POST /gateway.do HTTP/1.1\r\n");
            sb.append("Host: 10.30.10.151:8012\r\n");
            sb.append("Content-Length: " + data.length() + "\r\n");
            sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
            //注,這里很關(guān)鍵。這里一定要一個(gè)回車換行,表示消息頭完,不然服務(wù)器會(huì)等待
            sb.append("\r\n");
            osw.write(sb.toString());
            osw.write(data);
            osw.write("\r\n");
            osw.flush();
 
            //--輸出服務(wù)器傳回的消息的頭信息
            InputStream is = s.getInputStream();
            String line = null;
            int contentLength = 0;//服務(wù)器發(fā)送回來(lái)的消息長(zhǎng)度
            // 讀取所有服務(wù)器發(fā)送過(guò)來(lái)的請(qǐng)求參數(shù)頭部信息
            do {
                line = readLine(is, 0);
                //如果有Content-Length消息頭時(shí)取出
                if (line.startsWith("Content-Length")) {
                    contentLength = Integer.parseInt(line.split(":")[1].trim());
                }
                //打印請(qǐng)求部信息
                System.out.print(line);
                //如果遇到了一個(gè)單獨(dú)的回車換行,則表示請(qǐng)求頭結(jié)束
            } while (!line.equals("\r\n"));
 
            //--輸消息的體
            System.out.print(readLine(is, contentLength));
 
            //關(guān)閉流
            is.close();
 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /*
     * 這里我們自己模擬讀取一行,因?yàn)槿绻褂肁PI中的BufferedReader時(shí),它是讀取到一個(gè)回車換行后
     * 才返回,否則如果沒(méi)有讀取,則一直阻塞,直接服務(wù)器超時(shí)自動(dòng)關(guān)閉為止,如果此時(shí)還使用BufferedReader
     * 來(lái)讀時(shí),因?yàn)樽x到最后一行時(shí),最后一行后不會(huì)有回車換行符,所以就會(huì)等待。如果使用服務(wù)器發(fā)送回來(lái)的
     * 消息頭里的Content-Length來(lái)截取消息體,這樣就不會(huì)阻塞
     *
     * contentLe 參數(shù) 如果為0時(shí),表示讀頭,讀時(shí)我們還是一行一行的返回;如果不為0,表示讀消息體,
     * 時(shí)我們根據(jù)消息體的長(zhǎng)度來(lái)讀完消息體后,客戶端自動(dòng)關(guān)閉流,這樣不用先到服務(wù)器超時(shí)來(lái)關(guān)閉。
     */
    private static String readLine(InputStream is, int contentLe) throws IOException {
        ArrayList lineByteList = new ArrayList();
        byte readByte;
        int total = 0;
        if (contentLe != 0) {
            do {
                readByte = (byte) is.read();
                lineByteList.add(Byte.valueOf(readByte));
                total++;
            } while (total < contentLe);//消息體讀還未讀完
        } else {
            do {
                readByte = (byte) is.read();
                lineByteList.add(Byte.valueOf(readByte));
            } while (readByte != 10);
        }
 
        byte[] tmpByteArr = new byte[lineByteList.size()];
        for (int i = 0; i < lineByteList.size(); i++) {
            tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
        }
        lineByteList.clear();
 
        return new String(tmpByteArr, encoding);
    }
}

6. RestTemplate

RestTemplate 是由Spring提供的一個(gè)HTTP請(qǐng)求工具。比傳統(tǒng)的Apache和HttpCLient便捷許多,能夠大大提高客戶端的編寫效率。代碼如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}
 
 
@Autowired
RestTemplate restTemplate;
 
@Test
public void postTest() throws Exception {
    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
    Map paraMap = new HashMap();
    paraMap.put("type", "wx");
    paraMap.put("mchid", "10101");
    requestEntity.add("consumerAppId", "test");
    requestEntity.add("serviceName", "queryMerchant");
    requestEntity.add("params", JSON.toJSONString(paraMap));
    RestTemplate restTemplate = new RestTemplate();
    System.out.println(restTemplate.postForObject("http://10.30.10.151:8012/gateway.do",         requestEntity, String.class));
}

總結(jié)

到此這篇關(guān)于JAVA發(fā)送HTTP請(qǐng)求的多種方式的文章就介紹到這了,更多相關(guān)JAVA發(fā)送HTTP請(qǐng)求方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java8?LocalDateTime時(shí)間日期類使用實(shí)例詳解

    Java8?LocalDateTime時(shí)間日期類使用實(shí)例詳解

    本文從 LocalDateTime 類的創(chuàng)建、轉(zhuǎn)換、格式化與解析、計(jì)算與比較以及其他操作幾個(gè)方面詳細(xì)介紹了 LocalDateTime 類在 Java 8 中的使用,感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • Java動(dòng)態(tài)批量生成logback日志文件的示例

    Java動(dòng)態(tài)批量生成logback日志文件的示例

    本文主要介紹了Java動(dòng)態(tài)批量生成logback日志文件的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • 使用Java語(yǔ)言將XML轉(zhuǎn)為PDF的方法

    使用Java語(yǔ)言將XML轉(zhuǎn)為PDF的方法

    這篇文章主要介紹了使用Java語(yǔ)言將XML轉(zhuǎn)為PDF的方法,本文將介紹通過(guò)Java代碼來(lái)實(shí)現(xiàn)該格式轉(zhuǎn)換的方法,需要的朋友可以參考下
    2022-03-03
  • 聊聊BeanUtils.copyProperties和clone()方法的區(qū)別

    聊聊BeanUtils.copyProperties和clone()方法的區(qū)別

    這篇文章主要介紹了聊聊BeanUtils.copyProperties和clone()方法的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 解析Java中所有錯(cuò)誤和異常的父類java.lang.Throwable

    解析Java中所有錯(cuò)誤和異常的父類java.lang.Throwable

    這篇文章主要介紹了Java中所有錯(cuò)誤和異常的父類java.lang.Throwable,文章中簡(jiǎn)單地分析了其源碼,說(shuō)明在代碼注釋中,需要的朋友可以參考下
    2016-03-03
  • spring boot加載第三方j(luò)ar包的配置文件的方法

    spring boot加載第三方j(luò)ar包的配置文件的方法

    本篇文章主要介紹了spring boot加載第三方j(luò)ar包的配置文件的方法,詳細(xì)的介紹了spring boot jar包配置文件的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Spring中的事務(wù)隔離級(jí)別的介紹

    Spring中的事務(wù)隔離級(jí)別的介紹

    今天小編就為大家分享一篇關(guān)于Spring中的事務(wù)隔離級(jí)別的介紹,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • scala中的隱式類型轉(zhuǎn)換的實(shí)現(xiàn)

    scala中的隱式類型轉(zhuǎn)換的實(shí)現(xiàn)

    這篇文章主要介紹了scala中的隱式類型轉(zhuǎn)換的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • spring cloud gateway中redis一直打印重連日志問(wèn)題及解決

    spring cloud gateway中redis一直打印重連日志問(wèn)題及解決

    這篇文章主要介紹了spring cloud gateway中redis一直打印重連日志問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 關(guān)于Spring的@Transaction導(dǎo)致數(shù)據(jù)庫(kù)回滾全部生效問(wèn)題(又刪庫(kù)跑路)

    關(guān)于Spring的@Transaction導(dǎo)致數(shù)據(jù)庫(kù)回滾全部生效問(wèn)題(又刪庫(kù)跑路)

    使用@Transactional一鍵開(kāi)啟聲明式事務(wù), 這就真的事務(wù)生效了?過(guò)于信任框架總有“意外驚喜”。本文通過(guò)案例給大家詳解關(guān)于Spring的@Transaction導(dǎo)致數(shù)據(jù)庫(kù)回滾全部生效問(wèn)題,感興趣的朋友一起看看吧
    2021-05-05

最新評(píng)論

南投县| 绥滨县| 自贡市| 沾益县| 乌兰察布市| 阜宁县| 吉木萨尔县| 滨海县| 淮南市| 黄骅市| 桃源县| 兴安县| 通辽市| 尚志市| 水城县| 德化县| 南陵县| 蒙自县| 南江县| 亳州市| 乡宁县| 霸州市| 马龙县| 临洮县| 新野县| 交城县| 崇明县| 铅山县| 凤山市| 都匀市| 新蔡县| 铜川市| 全南县| 黄浦区| 句容市| 平乡县| 双牌县| 岳西县| 阳信县| 上思县| 博爱县|