JAVA 后台实现 https 请求——POST

 

需要引入相关的JAR包:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.RedirectLocations;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.ContentType;

maven 配置:

 

   <dependency>
  	<groupId>org.apache.commons</groupId>
  	<artifactId>commons-lang3</artifactId>
  	<version>3.1</version>
  </dependency>
  <dependency>
  	<groupId>bsh</groupId>
  	<artifactId>bsh</artifactId>
 	<version>1.3.0</version>
  </dependency>
  <dependency>
  	<groupId>net.sf.json-lib</groupId>
  	<artifactId>json-lib</artifactId>
  	<version>2.4</version>
  	<classifier>jdk15</classifier>
  </dependency>
  <dependency>
      <groupId>com.ning</groupId>
      <artifactId>async-http-client</artifactId>
      <version>1.9.40</version>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.3.2</version>
    </dependency>
    <dependency>

具体实现方法,根据服务器需要的json格式

public static JSONObject httpPost(String url, Object data) throws OApiException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().
        		setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
        	StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);
            
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                                   + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                JSONObject result = JSON.parseObject(resultStr);
                if (result.getInteger("errcode") == 0) {
                	result.remove("errcode");
                	result.remove("errmsg");
                    return result;
                } else {
                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    throw new OApiException(errCode, errMsg);
                }
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

 

转载于:https://my.oschina.net/xiaoshoubingliang/blog/808401

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java实现https post请求的示例代码: ```java import javax.net.ssl.HttpsURLConnection; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; public class HttpsPostExample { public static void main(String[] args) throws IOException { String url = "https://example.com/api"; String data = "{\"key\":\"value\"}"; URL apiUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) apiUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(data); outputStream.flush(); outputStream.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String responseLine; StringBuilder response = new StringBuilder(); while ((responseLine = reader.readLine()) != null) { response.append(responseLine); } reader.close(); System.out.println(response.toString()); } } ``` 其中,需要替换的部分包括: - `url`:需要发送https post请求的URL。 - `data`:需要发送的数据,可以是json格式的字符串或其他格式的字符串。 注意,由于本示例使用https协议,因此需要使用HttpsURLConnection类来建立连接。同时,还需要设置请求方法为POST,并设置请求头中的Content-Type为application/json,以便服务器正确解析请求。最后,通过DataOutputStream将需要发送的数据写入请求体中,然后获取服务器返回的数据并输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值