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

转载 2017年08月12日 23:11:59
一、只针对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; 
      
}
}

相关文章推荐

前段跨域 https到http请求

前段 https的站点(https://www.baidu.com) 向http(http://zi.baidu.cn)发送请求 问题1:https安全连接向http非安全连接发送请求 解...

http/https接口调用

java调用http/https接口,使用httpclient! 引入jar:commons-httpclient-3.1.0.jar baseclient,需要调用接口的继承此类,调用其中方法!...

HttpsURLConnection实现SSL的GET/POST请求

package org.nercita.weixin.util; import java.security.cert.CertificateException; import java.securi...

HttpClient学习笔记 --发送Http和Https请求

前言在前面有一章我转载过一篇关于HttpClient的文章:HttpClient使用详解,在那篇文章中详细讲解了HttpClient的特性,使用方法和实例。 这篇文章主要就上篇文章进一步浓缩,封装了...

如何在java中发起http和https请求

一般调用外部接口会需要用到http和https请求。 一.发起http请求 1.写http请求方法 //处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"...

HttpClient 发送 HTTP、HTTPS 请求的简单封装

序 最近这几周,一直在忙同一个项目,刚开始是了解需求,需求有一定了解之后,就开始调第三方的接口。由于第三方给提供的文档很模糊,在调接口的时候,出了很多问题,一直在沟通协调,具体的无奈就不说了,由于...

使用HttpClient发送https请求GET方式

第一步:封装查询参数,拼接url String url = "www.baidu.com?name=liufei"; 第二步:发出请求 HttpClient client = new ...

[通过HttpWebRequest请求https接口]

一.为什么进行代理接口的开发: 有些项目需要访问被墙了哒网站,比如前不久公司开发项目需要使用google地图的接口,而google在中国被墙了,所有打算做一个代理接口服务,将代理放到国外服务器上,通过...

整理了一下,真正可用的免费的https、http接口,测试接口可以使用

我搜了一下开放式的接口,往上大同小异,基本上都是抄来抄去,有些接口早就不能用了,也是直接转载,我做了一下排除,留下了真正的能用的一些免费接口,希望能对大家有所帮助吧。这些接口截至2017.3.10 发...

Java 发送https 的post请求方法

import java.io.BufferedReader;   import java.io.FileInputStream;   import java.io.IOException;   ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:https和http协议接口post请求接口方法
举报原因:
原因补充:

(最多只允许输入30个字)