若不用jsonp,可使用httpClient请求数据

当你使用多个服务器进行协同提供服务时,会存在跨域请求数据的情况,除了使用jsonp外,还可以使用apache的httpClient进行请求数据。

httpClient在service层被调用,请求到的数据,可能是json数据,也可能是html代码。

以下是httpClient的辅助工具类,直接调用即可。

httpClientUtil.java

package com.taotao.utils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
时间: 2024-08-01 10:42:00

若不用jsonp,可使用httpClient请求数据的相关文章

Httpclient请求数据(post)

public static String loginCheck_POST_HttpClient(String name,String pass,String url){ String result = ""; HttpPost post = new HttpPost(url);//创建httpClient的post请求对象 //设置请求参数 HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnec

不用jsonp实现跨域请求

这几天要用到跨域请求,我在网上找了好多资料,最后自己研究出来一个比较简单方便的, 请求的过程和jquery普通的ajax一样.我用的是.net平台 ,IIS7.5 来看一下后台的代码,我是用MVC的Controll做数据接口. 接下来是前台代码了: <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitio

Httpclient请求数据

package com.baidu.myutils; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.cli

使用JSONP跨域请求数据

下面代码,可以使用JSONP进行跨域请求数据,Insus.NET记录以下,以备忘记. 使用JSONP跨域请求数据

get和post方式请求数据,jsonp

get方式请求数据: p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 19.0px Consolas; color: #289c97 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 19.0px Consolas; color: #060606 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 19.0px Consolas; color: #4663cc }

android通过httpClient请求获取JSON数据并且解析

android通过httpClient请求获取JSON数据并且解析:http://www.cnblogs.com/gzggyy/archive/2013/05/08/3066288.html Android--使用Http向服务器发送请求并取得返回结果,下载图片:http://www.2cto.com/kf/201307/229489.html Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据):http://blog.csdn.net/he

HttpClient的Post请求数据

最近在项目中需要添加Post请求数据,以前的Get请求是使用JDK自带的URLConnection.在项目组人员的推荐下,开始使用HttpClient. HttpClient简介: HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包, 并且它支持HTTP协议最新的版本和建议.HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus 和HTMLUn

android菜鸟学习笔记24----与服务器端交互(一)使用HttpURLConnection和HttpClient请求服务端数据

主要是基于HTTP协议与服务端进行交互. 涉及到的类和接口有:URL.HttpURLConnection.HttpClient等 URL: 使用一个String类型的url构造一个URL对象,如: URL url = new URL(http://10.0.2.2/index.php); openConnection()方法返回一个对指定url的资源的连接.返回类型是URLConnection,但是,由于这里我们一般用的是http协议,所以返回的实际是HttpURLConnection对象,故一

httpclient + AsyncTask 请求数据 || httpclient + handler 请求数据

public class MyAsy extends AsyncTask<String, Integer, String> { private String json; @Override    protected String doInBackground(String... params) {        // TODO Auto-generated method stub        // 实例化HttpClient        HttpClient client = new De