Rumah  >  Artikel  >  Java  >  Apakah cara untuk menghantar permintaan HTTP dalam JAVA?

Apakah cara untuk menghantar permintaan HTTP dalam JAVA?

王林
王林ke hadapan
2023-04-15 09:04:05994semak imbas

1. HttpURLConnection

Gunakan jaring yang disediakan oleh JDK secara asli, tiada pakej balang lain diperlukan, kodnya adalah seperti berikut:

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,此处根据实际情况确定
            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");
            //组装入参
            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 >needs commons- httpclient-3.1.jar, maven dependencies adalah seperti berikut:

Kodnya adalah seperti berikut:
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

3 CloseableHttpClient
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,此处根据实际情况确定
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        //必须设置下面这个Header
        //添加请求参数
        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();
        }
    }
}

untuk menggunakan httpclient-4.5.6.jar , kebergantungan maven adalah seperti berikut:

Kodnya adalah seperti berikut:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

4 okhttp
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();
            }
        }
    }
}

perlu menggunakan okhttp-3.10.0.jar, dan kebergantungan maven adalah seperti berikut:

Kodnya adalah seperti berikut:
<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>3.10.0</version>
</dependency>

5 🎜> Gunakan jaring yang disediakan secara asli oleh JDK tanpa memerlukan pakej balang lain
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);
        }
    }
}

Kod adalah seperti berikut:

6. Alat permintaan HTTP disediakan oleh Spring. Ia jauh lebih mudah daripada Apache dan HttpCLient tradisional, dan boleh meningkatkan kecekapan penulisan pelanggan. Kodnya adalah seperti berikut:

Atas ialah kandungan terperinci Apakah cara untuk menghantar permintaan HTTP dalam JAVA?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:yisu.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam