https和http协议接口post请求接口方法

一、只针对http 的post请求
package test;

import java.io.InputStreamReader;
import java.net.URI;

import net.sf.json.JSONObject;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpClientRequest {

public static String post(String url,JSONObject json, String token){
String result = null;
        HttpClient client = new DefaultHttpClient();  
        HttpPost request;  
        try {  
            request = new HttpPost(new URI(url)); 
            if(json != null){
            StringEntity s = new StringEntity(json.toString(),"utf-8");
s.setContentType("application/json");
request.setEntity(s);
            }
            if(token != null){
            request.setHeader("token", token);
            }
            
            HttpResponse response = client.execute(request); 
            int returncode = response.getStatusLine().getStatusCode();
            System.out.println("Response Code:"+returncode);
            if (returncode == 200) {
            Header[] header = response.getHeaders("token");
            if(header.length >0){
            for(Header h:header){
            System.out.println(h.getName()+" "+h.getValue());
            }
            }
            HttpEntity entity = response.getEntity();
            long contentLen = entity.getContentLength();
            if(contentLen == 0){
            return "User Has No Authority";
            }
String charset = EntityUtils.getContentCharSet(entity);
InputStreamReader isr = new InputStreamReader(entity.getContent(), charset);
StringBuffer sb = new StringBuffer();
char[] ct = new char[64];
int len = 0;
while((len = isr.read(ct))!=-1){
String sst = new String(ct);
sst = sst.substring(0, len).trim();
sb.append(sst);
}
result = sb.toString().replace("\\\"", "\"");
result = result.substring(1, result.length()-1);
            }
        } catch(Exception e) {
        e.printStackTrace();
        }
        return result;
}
}


二、针对https和http都可以的post请求
package https;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.FileNameMap;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.ProtocolException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpsUtil{
static class TrustAnyTrustManager implements X509TrustManager{

@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}

@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}

@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
static class TrustAnyHostnameVerifier implements HostnameVerifier{

@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
}
/**
* post方式请求服务器(https协议)
* @param url
*            请求地址
* @param content
*            参数
* @param charset
*            编码
* @return
 * @throws URISyntaxException 
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
static public String SendHttpsPOST(String url,JSONObject json, String token) throws URISyntaxException 
String result = null;
        HttpClient client = new DefaultHttpClient();  
        HttpPost request;  
        try {  
            request = new HttpPost(new URI(url)); 
            if(json != null){
            StringEntity s = new StringEntity(json.toString(),"utf-8");
s.setContentType("application/json");
request.setEntity(s);
            }
            if(token != null){
            request.setHeader("token", token);
            }
            //设置SSLContext 
            SSLContext sslcontext = SSLContext.getInstance("TLS"); 
            sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, null);

            //打开连接
        //要发送的POST请求url?Key=Value&Key2=Value2&Key3=Value3的形式 
            SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext); 
            
            client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
            HttpResponse response = client.execute(request); 
            int returncode = response.getStatusLine().getStatusCode();
            System.out.println("Response Code:"+returncode);           
           
            if (returncode == 200) {
            Header[] header = response.getHeaders("token");
            if(header.length >0){
            for(Header h:header){
            System.out.println(h.getName()+" "+h.getValue());
            }
            }
            HttpEntity entity = response.getEntity();
            long contentLen = entity.getContentLength();
            if(contentLen == 0){
            return "User Has No Authority";
            }
String charset = EntityUtils.getContentCharSet(entity);
InputStreamReader isr = new InputStreamReader(entity.getContent(), charset);
StringBuffer sb = new StringBuffer();
char[] ct = new char[64];
int len = 0;
while((len = isr.read(ct))!=-1){
String sst = new String(ct);
sst = sst.substring(0, len).trim();
sb.append(sst);
}
result = sb.toString().replace("\\\"", "\"");
result = result.substring(1, result.length()-1);
            } 
        } catch (KeyManagementException e) { 
            e.printStackTrace(); 
        } catch (NoSuchAlgorithmException e) { 
            e.printStackTrace(); 
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        } catch (ProtocolException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
        return result; 
      
}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用HttpURLConnection或者Apache HttpClient来发送HTTP请求。其中,HttpURLConnection是Java标准库中提供的类,它可以通过向服务器发送不同的HTTP请求方法(如GET、POST等)来实现与服务器的交互。Apache HttpClient是一个第三方库,相对于HttpURLConnection来说,它提供了更多的功能和更简洁的API接口。 下面以HttpURLConnection为例介绍如何发送POST请求: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpPostExample { public static void main(String[] args) throws IOException { String url = "http://example.com/api/v1/user"; // 请求的url地址 String body = "{\"username\":\"test\",\"password\":\"123456\"}"; // 请求体 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置请求方法POST con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // 设置请求头 con.setDoOutput(true); // 允许输出流 // 发送请求体 try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8); wr.write(bodyBytes); wr.flush(); } // 处理响应结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println("Response Body : " + response.toString()); } } } ``` 以上代码演示了如何使用HttpURLConnection发送POST请求,其中`url`表示请求的url地址,`body`表示请求体,需要根据实际情况进行修改。在发送请求时,需要设置请求方法POST,并设置请求头`Content-Type`为`application/json; charset=UTF-8`。在发送请求体后,可以通过`getResponseCode`方法获取响应状态码,通过`getInputStream`方法获取响应内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值