java调用http接口并解析返回的json对象(URLConnection、HttpURLConnection、HttpClien)三种方式

URLConnection方式:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

public class Test {

    //调用http接口
    @RequestMapping(value="testInterfaces.htm", method={RequestMethod.GET, RequestMethod.POST})
    public void testInterfaces(HttpServletRequest request) throws Exception{
        //传入中文参数并设置编码格式
        String param = "{\"url\":\"中文\"}";
        param = URLEncoder.encode(param, "UTF-8");
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
               URL realUrl = new URL("http://localhost/test.htm");
               // 打开和URL之间的连接
               URLConnection conn = realUrl.openConnection();
               // 发送POST请求必须设置如下两行
               conn.setDoOutput(true);
               conn.setDoInput(true);
               // 获取URLConnection对象对应的输出流
               out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
               // 发送请求参数
               out.print(param);          
               // flush输出流的缓冲
               out.flush();
               // 定义BufferedReader输入流来读取URL的响应
               in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
               String line;
               while ((line = in.readLine()) != null) {
                   result += line;
               }
               //解析json对象
               JSONObject jsStr = JSONObject.fromObject(result);
               System.out.println(jsStr.get("firstName"));
            } catch (Exception e) {
               e.printStackTrace();
            }
    }
    
    //所调用的接口
    @RequestMapping(value = "test.htm", method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public JSONObject test(HttpServletRequest request)throws Exception {       
        JSONObject jsonObj = new JSONObject();
        Map map = new HashMap();
        map.put("firstName", "jack");
        jsonObj.putAll(map);
        return jsonObj;
    }

}
HttpURLConnection的POST方式:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

//HttpURLConnection发送POST请求
public class HttpURLConnectionPost {

	public static void main(String[] args) throws Exception{
		String param = "id=123456&name=aaa";
		PrintWriter out = null;
        BufferedReader in = null;
        try {
	        //获取访问地址URL
	        URL url = new URL("http://localhost:8801/httpUrlPost");
	        //创建HttpURLConnection对象
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        //设置请求格式
			conn.setRequestProperty("Content-type", "application/json");
			//设置编码语言
			conn.setRequestProperty("Accept-Charset", "UTF-8");
	        //请求方式,默认是GET
	        conn.setRequestMethod("POST");
	        //连接主机的超时时间(单位:毫秒)
		    conn.setConnectTimeout(30000);
		    //从主机读取数据的超时时间(单位:毫秒)
		    conn.setReadTimeout(30000); 
	        //设置是否输出,post请求参数要放在 http正文内,需设为true,默认是false
	        conn.setDoOutput(true);
	        //设置是否读入,默认是true
	        conn.setDoInput(true);
	        //获取字符输出流
	        out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
	        //发送请求参数
	        out.print(param);          
	        //刷新输出流
	        out.flush();
	        //关闭输出流
	        out.close();
	        String result = "";
	        int code = conn.getResponseCode();
	        if(code == 200){
	        	//定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
	            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	            //关闭输入流
	            in.close();
	        }
	        System.out.println("返回结果:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
HttpURLConnection的GET方式:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

//HttpURLConnection发送GET请求
public class HttpURLConnectionGet {

	public static void main(String[] args) throws Exception{
        BufferedReader in = null;
        try {
	        //获取访问地址URL,注意GET请求若URL中包含中文字符的话,在高版本TOMCAT中会认为是不合法字符,可改为POST方式
	        URL url = new URL("http://localhost:8801/httpUrlPost?id=123456&name=aaa");
	        //创建HttpURLConnection对象
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        //请求方式,默认是GET
	        conn.setRequestMethod("GET");
	        //连接主机的超时时间(单位:毫秒)
		    conn.setConnectTimeout(30000);
		    //从主机读取数据的超时时间(单位:毫秒)
		    conn.setReadTimeout(30000); 
	        //设置是否输出,默认是false
	        conn.setDoOutput(false);
	        //设置是否读入,默认是true
	        conn.setDoInput(true);
	        String result = "";
	        int code = conn.getResponseCode();
	        if(code == 200){
	        	//定义BufferedReader输入流读取响应,getInputStream()会自动建立连接,无需手动调用connect()连接
	            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	            //关闭输入流
	            in.close();
	        }
	        System.out.println("返回结果:"+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

HttpClient的POST方式:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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;

//HttpClient发送POST请求
public class HttpClientPost {

	public static void main(String[] args) throws Exception{
		String result = "";
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			//创建HttpClient对象
			httpClient = HttpClients.createDefault();
			//创建HttpPost对象
			HttpPost httpPost = new HttpPost("http://localhost:8801/httpUrlPost");
			//设置参数
			List params = new ArrayList();
	        params.add(new BasicNameValuePair("id", "123456"));
	        params.add(new BasicNameValuePair("name", "张三"));
	        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)//设置连接超时时间
                    .setConnectionRequestTimeout(30000)//从连接池获取连接超时时间
                    .setSocketTimeout(30000)//设置读取数据超时时间
                    .build();
			httpPost.setConfig(requestConfig);
			response = httpClient.execute(httpPost);
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭资源
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} 
        System.out.println("返回结果:"+result);
	}
}

HttpClient的GET方式:
import java.io.IOException;

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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

//HttpClient发送GET请求
public class HttpClientGet {

	public static void main(String[] args) throws Exception{
		String result = "";
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			//创建HttpClient对象
			httpClient = HttpClients.createDefault();
			//创建HttpGet对象
			HttpGet httpGet = new HttpGet("http://localhost:8801/httpUrlPost?id=123456&name=张三");
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)//设置连接超时时间
                    .setConnectionRequestTimeout(30000)//从连接池获取连接超时时间
                    .setSocketTimeout(30000)//设置读取数据超时时间
                    .build();
			httpGet.setConfig(requestConfig);
			response = httpClient.execute(httpGet);
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭资源
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} 
        System.out.println("返回结果:"+result);
	}
}

注意:此HttpClient用法支持4.5.x版本,示例所依赖的jar包为httpclient-4.5.5.jar、httpcore-4.4.9.jar

你可能感兴趣的:(java工具类)