Java之Json数据格式调用第三方接口

点击下载JSON格式操作类库

使用元原始的HttpURLConnection来调用第三方接口

package com.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpUtil {
	/**
	 * Json格式提交数据到第三方接口,并返回数据
	 * @param url 第三方接口地址
	 * @param param 数据参数,JSON格式,可以为null
	 */
	public static String doPost(String urlStr,String param){
		HttpURLConnection connection = null;
		InputStream is = null;
		InputStreamReader rsd = null;
		BufferedReader br = null;
		OutputStream os = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		StringBuffer sb = new StringBuffer();
		
		try {
			URL url = new URL(urlStr);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);	//不缓存
			connection.setRequestProperty("connection", "Keep-Alive");	//设置保活连接
			connection.setRequestProperty("charset", "UTF-8");			//提交的数据编码
			connection.setRequestProperty("Content-type", "application/json");	//提交的数据格式
			connection.setRequestProperty("accept", "application/json");		//接收的数据格式
			connection.setConnectTimeout(30000);	//30秒连接超时
			connection.setReadTimeout(30000);		//30秒读取超时
			connection.connect();
			if(param != null && !"".equals(param)){
				os = connection.getOutputStream();
				osw = new OutputStreamWriter(os);		
				bw = new BufferedWriter(osw);
				bw.write(param);
				bw.flush();
			}
			int status = connection.getResponseCode();
			if(status == 200){
				is = connection.getInputStream();
				rsd = new InputStreamReader(is,"UTF-8");
				br = new BufferedReader(rsd);
				String s;
				while((s = br.readLine()) != null){
					sb.append(s);
				}
			}else{
				return "{\"ResuleState\":\"-1\",\"Msg\":\"连接异常\"}";
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
				try {
					if(br != null)br.close();
					if(rsd != null)rsd.close();
					if(is != null)is.close();
					if(bw != null)bw.close();
					if(osw != null)osw.close();
					if(os != null)os.close();
					if(connection != null) connection.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return sb.toString();
	}
}

使用HttpClient类库调用第三方接口

点击下载HttpClient类库

package com.service;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil2 {
	/** 
     * post请求(用于请求json格式的参数) 
     * @param url 接口地址
     * @param params 接口参数
     * @return 
     */  
    public static String doPost(String url, String params) {      
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        HttpPost httpPost = new HttpPost(url);// 创建httpPost     
        httpPost.setHeader("Accept", "application/json");    //接收报文类型
        httpPost.setHeader("Content-Type", "application/json");   //发送报文类型
        if(params != null && !"".equals(params)){
            StringEntity entity = new StringEntity(params, "UTF-8");  
            httpPost.setEntity(entity);    	
        }     
        CloseableHttpResponse response = null;     
        try {  
            response = httpclient.execute(httpPost);  
            StatusLine status = response.getStatusLine();  
            int state = status.getStatusCode();  
            if (state == HttpStatus.SC_OK) {  
                HttpEntity responseEntity = response.getEntity();  
                String jsonString = EntityUtils.toString(responseEntity,"UTF-8");  
                return jsonString;  
            }  
            else{  
                System.out.println(state);
            }  
        } catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
        finally { 
                try {  
                	if (response != null)response.close();  
                	httpclient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
        }  
        return null;  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值