ホームページ > Java > &#&チュートリアル > Javaはnew HttpPost(URL)とnew URL(shixun_ip)を操作してストリームを取得します

Javaはnew HttpPost(URL)とnew URL(shixun_ip)を操作してストリームを取得します

(*-*)浩
リリース: 2019-10-29 15:17:03
転載
3435 人が閲覧しました

Javaはnew HttpPost(URL)とnew URL(shixun_ip)を操作してストリームを取得します

HttpClient:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

private static HttpClient httpClient;

    static {

        if (httpClient == null) {

            HttpParams params = new BasicHttpParams();

            // 设置一些基本参数

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

            // 超时设置 /* 从连接池中取连接的超时时间 */

            ConnManagerParams.setTimeout(params, 1000);

            /* 连接超时 */

            HttpConnectionParams.setConnectionTimeout(params, 2000);

            /* 请求超时 */

            HttpConnectionParams.setSoTimeout(params, 4000);

            SchemeRegistry schReg = new SchemeRegistry();

            schReg.register(new Scheme("http", PlainSocketFactory

                    .getSocketFactory(), 80));

            schReg.register(new Scheme("https", SSLSocketFactory

                    .getSocketFactory(), 443));

            // 使用线程安全的连接管理来创建HttpClient

            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(

                    params, schReg);

            httpClient = new DefaultHttpClient(conMgr, params);

        }

    }

@SuppressWarnings("unchecked")

    private <T> T getJsonObjectFromUrl(String urlStr,

            List<NameValuePair> params, Class<T> className) throws Exception{

        T object = null;

  

        InputStream in = null;

        try {

            HttpPost httpPost = new HttpPost(urlStr);

  

            if (params != null) {

                //              List<NameValuePair> nvps = new ArrayList<NameValuePair>();

                //              for (Entry<String, String> entry : params.entrySet()) {

                //                  nvps.add(new BasicNameValuePair(entry.getKey(), entry

                //                          .getValue()));

                //              }

                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            }

            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

  

            if(entity!=null){

                in= entity.getContent(); //之前没使用这个造成了大量异常抛出

            }

  

            /*String s = EntityUtils.toString(in, "UTF-8");

            if (entity != null) {

                EntityUtils.consume(entity);

            }*/

  

            String s = inputStream2String(in,"UTF-8");

            JsonResult jsonResult = (JsonResult)JSONObject.parseObject(s, JsonResult.class);

            if(jsonResult.getCode() == 200){

                Object obj = jsonResult.getData();

  

                if(obj != null){

                    if(className.isInstance(obj)){

                        object = (T)(obj);

                    }

                    else if(obj instanceof JSONObject){

                        object= JSONObject.parseObject(obj.toString(), className);

                    }                  

                }

            }else{

                throw new Exception(jsonResult.getMsg());

            }

  

            if(in!=null){

                in.close();

            }

  

        } catch (Exception e) {

            throw e;

        }

  

        return object;

    }

ログイン後にコピー

新しい URL():

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

try{

                     

<span style="white-space:pre">                    </span>//省略

                    URL shixun = new URL(url);

                    InputStream in = shixun.openStream();

  

                     

                    long end = System.currentTimeMillis(); 

                    if((end-start)<=5000){  //5s内不响应就跳过

                         

                        String ret = cn.com.jsoft.jframe.utils.StringUtils.toString(in, "utf-8");

                        JSONObject obj = JSONObject.fromObject(ret);

                        if(obj!=null&&obj.getJSONObject("info")!=null&&obj.containsKey("info")==true){

                            JSONObject info = obj.getJSONObject("info");

                            JSONArray data = info.getJSONArray("data");

                            if(data!=null&&data.size()>0){

                                for(int i=0;i<data.size();i++){

                                    JSONObject entry = data.getJSONObject(i);

                                     

                                }

                            }

                        }

                        in.close();

                    }

  

                }catch (Exception e) {

                    e.printStackTrace();

                }

ログイン後にコピー

Java はInputStream を文字列に変換#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

public static String inputStream2String(InputStream is, String charset) {

        ByteArrayOutputStream baos = null;

  

        try {

            baos = new ByteArrayOutputStream();

            int i = -1;

            while ((i = is.read()) != -1) {

                baos.write(i);

            }

            return baos.toString(charset);

        } catch (IOException e) {

            e.printStackTrace();

            logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"

                    + e.getMessage());

        } finally {

            if (null != baos) {

                try {

                    baos.close();

                } catch (IOException e) {

                    e.printStackTrace();

                    logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"

                            + e.getMessage());

                }

                baos = null;

            }

        }

  

        return null;

    }

ログイン後にコピー

以上がJavaはnew HttpPost(URL)とnew URL(shixun_ip)を操作してストリームを取得しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
ヘルプ: JAVA 暗号化データ PHP 復号化
から 1970-01-01 08:00:00
0
0
0
JAVAをインストールする
から 1970-01-01 08:00:00
0
0
0
Javaをインストールできません
から 1970-01-01 08:00:00
0
0
0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート