第一种:使用Java自带的jdk,将返回结果转成json格式

   

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

       String url = "http://www.baidu.com";   

           try{
                 HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
                 con.setRequestMethod("GET");
                 con.setDoOutput(true);
                 InputStream in =con.getInputStream();
                  BufferedReader rd = new BufferedReader(new InputStreamReader(in,"UTF-8"));
                  StringBuffer entity = new StringBuffer();
                  String str = null;
                  while((str = rd.readLine()) != null){
                           entity.append(str);
                    }
                    jsonResult = JSONObject.fromObject(entity.toString());
                 }catch(Exception e){
       e.printStackTrace();       
                 }

    

第二种:使用httpclientjar包实现

          

import org.apache.http.HttpEntity;
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;

 

关键代码:

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = null;
        JSONObject jsonResult = null;
        try{
             httpGet = new HttpGet(url);
             CloseableHttpResponse response = httpClient.execute(httpGet);
             HttpEntity entity = response.getEntity();
             jsonResult = JSONObject.fromObject(EntityUtils.toString(entity));
        }catch(Exception e){
             e.printStackTrace();
       }finally{
             if(httpGet!=null){
                   httpGet.releaseConnection();
             }
             if(httpClient!=null){
                    try {
                          httpClient.close();
                     } catch (IOException e) {
                                 e.printStackTrace();
                    }
              }
}

System.out.println(jsonResult);

 

第三种:访问https,以及使用POST方式提交

public class MyXTrustManager implements X509TrustManager {

    public MyXTrustManager() {
    }

    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

}

public class HttpsPostTest {
    
    private static String httpUrl  = "https://weixin.qq.com/sms/api/index/index";
    
    public void sendMessage(String userId,String content){
        try {
            // https添加ssl
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyXTrustManager()};
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            
            URL urls = new URL(httpUrl);
            HttpsURLConnection con = (HttpsURLConnection) urls.openConnection();
            con.setSSLSocketFactory(ssf);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // POST 以流的形式传递参数
            String contents = "id=123&name=xxxx";
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.write(contents.getBytes("UTF-8"));
            out.flush();
            out.close();
            
            InputStream in = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
            StringBuffer sb = new StringBuffer();
            String s ;
            while((s = br.readLine()) != null){
                sb.append(s);
            }
            br.close();
            in.close();
            System.out.println(sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }
}

 

 httpclient4.5 jar包下载地址:http://download.csdn.net/download/h785193391/8902265

posted on 2017-07-20 15:56  hello策  阅读(830)  评论(0编辑  收藏  举报