溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JAVA發(fā)送HTTP請求的方式有哪些

發(fā)布時間:2023-02-01 09:14:26 來源:億速云 閱讀:122 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“JAVA發(fā)送HTTP請求的方式有哪些”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“JAVA發(fā)送HTTP請求的方式有哪些”文章能幫助大家解決問題。

1. HttpURLConnection

使用JDK原生提供的net,無需其他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");
            //得到連接對象
            con = (HttpURLConnection) url.openConnection();
            //設置請求類型
            con.setRequestMethod("POST");
            //設置Content-Type,此處根據(jù)實際情況確定
            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());
            //得到響應碼
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到響應流
                InputStream inputStream = con.getInputStream();
                //將響應流轉換成字符串
                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", "*/*");
        //設置Content-Type,此處根據(jù)實際情況確定
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //必須設置下面這個Header
        //添加請求參數(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;// 命名沖突,換一個名字,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,無需其他jar包

代碼如下:

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");
            //注,這里很關鍵。這里一定要一個回車換行,表示消息頭完,不然服務器會等待
            sb.append("\r\n");
            osw.write(sb.toString());
            osw.write(data);
            osw.write("\r\n");
            osw.flush();
 
            //--輸出服務器傳回的消息的頭信息
            InputStream is = s.getInputStream();
            String line = null;
            int contentLength = 0;//服務器發(fā)送回來的消息長度
            // 讀取所有服務器發(fā)送過來的請求參數(shù)頭部信息
            do {
                line = readLine(is, 0);
                //如果有Content-Length消息頭時取出
                if (line.startsWith("Content-Length")) {
                    contentLength = Integer.parseInt(line.split(":")[1].trim());
                }
                //打印請求部信息
                System.out.print(line);
                //如果遇到了一個單獨的回車換行,則表示請求頭結束
            } while (!line.equals("\r\n"));
 
            //--輸消息的體
            System.out.print(readLine(is, contentLength));
 
            //關閉流
            is.close();
 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /*
     * 這里我們自己模擬讀取一行,因為如果使用API中的BufferedReader時,它是讀取到一個回車換行后
     * 才返回,否則如果沒有讀取,則一直阻塞,直接服務器超時自動關閉為止,如果此時還使用BufferedReader
     * 來讀時,因為讀到最后一行時,最后一行后不會有回車換行符,所以就會等待。如果使用服務器發(fā)送回來的
     * 消息頭里的Content-Length來截取消息體,這樣就不會阻塞
     *
     * contentLe 參數(shù) 如果為0時,表示讀頭,讀時我們還是一行一行的返回;如果不為0,表示讀消息體,
     * 時我們根據(jù)消息體的長度來讀完消息體后,客戶端自動關閉流,這樣不用先到服務器超時來關閉。
     */
    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提供的一個HTTP請求工具。比傳統(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));
}

關于“JAVA發(fā)送HTTP請求的方式有哪些”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識,可以關注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI