java后台使用HttpClient发起请求,解析返回的数据

    //编码格式
    public static final String DEFAULT_CONTENT_ENCODING = "UTF-8";
    //超时时间
    public static final int CONN_TIME_OUT = 20000;
    //读取超时时间
    public static final int SO_TIME_OUT = 20000;

    private static ClientConnectionManager connectionManager;


    /**
     * 发送报文
     * @param url 访问地址
     * @param params	请求参数
     * @return
     */
    public static JSONObject httpRequest(String url, List params){

        StringBuffer result = new StringBuffer();

        HttpClient httpclient = getHttpClient(CONN_TIME_OUT,SO_TIME_OUT);

        HttpPost post = null;
        try {
            URL url1 = new URL(url);
            URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
            post = new HttpPost(uri);
            HttpEntity requestEntity = new UrlEncodedFormEntity(params, "UTF-8");
            post.setEntity(requestEntity);
            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            InputStreamReader reader = new InputStreamReader(resEntity.getContent(), DEFAULT_CONTENT_ENCODING);
            char[] buff = new char[1024];
            int length = 0;
            while ((length = reader.read(buff)) != -1) {
                result.append(buff, 0, length);
            }
            if(response.getStatusLine().getStatusCode() >= 400) {
                throw  new RuntimeException("远程服务器异常,【错误码:" + response.getStatusLine().getStatusCode() + "】");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            post.releaseConnection();
        }

        return (net.sf.json.JSONObject) JSONSerializer.toJSON(result.toString());
    }

    /**
     * 创建带超时参数的httpClient
     * @param timeOut 链接超时
     * @param soTimeout	读取超时
     * @return
     */
    public static HttpClient getHttpClient(int timeOut, int soTimeout) {

        if (timeOut == 0) {
            timeOut = CONN_TIME_OUT;
        }
        if (soTimeout == 0) {
            soTimeout = SO_TIME_OUT;
        }

        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        DefaultHttpClient httpclient = new DefaultHttpClient(connectionManager, params);
        return httpclient;
    }

调用实例:

    //构造参数
    List params = new ArrayList();
    params.add(new BasicNameValuePair("接口参数1", "value1");
    params.add(new BasicNameValuePair("接口参数2", "value2"));

    httpRequest("具体接口url", params);

 

你可能感兴趣的:(java)