HttpClient 4 访问远程服务

1.带ssl证书

public static JSONObject httpsRequest(String requestUrl, String method, String data) {
        JSONObject jsonObject = null;
        StringBuffer sb = new StringBuffer();

        try {
            //创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance( "SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());

            //获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            //创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);

            //设置连接参数
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(method);//设置请求方式

            if (method.equals( "GET")) {
                conn.connect();
            }
            if (data != null) {
                OutputStream os = conn.getOutputStream();
                os.write(data.getBytes( "utf-8"));
                os.close();
            }

            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,  "utf-8");
            BufferedReader br = new BufferedReader(isr);

            String str = null;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            //清理
            br.close();
            isr.close();
            is.close();
            is = null;
            conn.disconnect();
            //转化为JSON对象
            jsonObject = JSONObject.parseObject(sb.toString());

        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;

    }
2.发送post请求
/**
     * post请求(用于key-value格式的参数)
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map params){


        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient client = new DefaultHttpClient();
            // 实例化HTTP方法
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));


            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));


                //System.out.println(name +"-"+value);
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }


                in.close();


                return sb.toString();
            }
            else{   //
                System.out.println("状态码:" + code);
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();


            return null;
        }
    }

3.发送post请求另一种形式

/**
     * post请求(用于请求json格式的参数)
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "text/plain;charset=utf-8");
        httpPost.setHeader("Content-Type", "text/plain;charset=utf-8");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        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);
                return jsonString;
            }
            else{
                logger.error("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
4.发送post请求用于传输文件
/**
     * post请求(用于请求file传输)
     * @param url
     * @param instream
     * @return
     */
    public static String doPost(String url, InputStream instream) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/octet-stream");
        httpPost.setHeader("Content-Type", "application/octet-stream");
        String charSet = "UTF-8";
        CloseableHttpResponse response = null;

            httpPost.setEntity(new InputStreamEntity(instream));

        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);
                return jsonString;
            }
            else{
                logger.error("请求返回:"+state+"("+url+")");
            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

5.发送post用于下载文件

/**
     * 用于下载文件
     * flag : 用于数据摆渡 , 输出流转换输入流  true为转换
     */
    public static Map<String, Object> doPostDownLoad(String url,  Map params, OutputStream fos, boolean flag) {
    	 BufferedReader in = null;
         try {
             // 定义HttpClient
             HttpClient client = new DefaultHttpClient();
             // 实例化HTTP方法
             HttpPost request = new HttpPost();
             request.setHeader("Content-Type", "*/*");
             request.setURI(new URI(url));

             //设置参数
             request.setEntity(new StringEntity(FastJsonUtils.toJSONString(params))); 
             HttpResponse response = client.execute(request);
             int code = response.getStatusLine().getStatusCode();
             if(code == 200){    //请求成功
            	 Map<String, Object> mapResult = new HashMap<String, Object>();
            	 mapResult.put("isSuccess", true);
            	 if (flag) {
            		 ByteArrayOutputStream bos = new ByteArrayOutputStream();
            		 response.getEntity().writeTo(bos);
            		 ByteArrayInputStream swapInputStream = new ByteArrayInputStream(bos.toByteArray());
            		 mapResult.put("inputStream", swapInputStream);
            		 
            	 } else {
            		 response.getEntity().writeTo(fos);
            	 }
            	 return mapResult;
             }
             else{   //
                 System.out.println("状态码:" + code);
                 return null;
             }
         }
         catch(Exception e){
             e.printStackTrace();
             return null;
         }
    }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值