Android HttpUrlConnection没有错误也没有结果

时间:2017-05-30 16:07:39

标签: android httpurlconnection

我确实喜欢这个。我想打电话给rest api。 'urlString'是url示例。 但我看不到任何东西。没有错误,没有结果。 我能怎么做? (LogManager在Android Monitor logcat中打印String)。

btnCar.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {              

        final String urlString = "https://apis.skplanetx.com/tmap/routes?version=1&appKey='MyPersonalAPIkey'&startX=14368651.605895586&startY=4188210.3283031476&endX=14135591.321771959&endY=4518111.822510956&reqCoordType=EPSG3857&resCoordType=EPSG3857&tollgateFareOption=8"; // url example

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                        LogManager.printLog(urlString);
                        URL url = new URL(urlString);

                        HttpURLConnection http = (HttpURLConnection) url.openConnection();

                        http.setDefaultUseCaches(false);
                        http.setDoInput(true);
                        http.setDoOutput(true);
                        http.setRequestMethod("POST");
                        http.setRequestProperty("content-type", "application/x-www-form-urlencoded");

                        OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "UTF-8");
                        PrintWriter writer = new PrintWriter(outStream);
                        writer.flush();

                        InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "UTF-8");
                        BufferedReader reader = new BufferedReader(tmp);
                        StringBuilder builder = new StringBuilder();
                        String strResult;
                        while ((strResult = reader.readLine()) != null) {
                            builder.append(strResult + "\n");

                        }
                        LogManager.printLog("result: " + builder.toString());


                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
    }
}

1 个答案:

答案 0 :(得分:0)

我运行了你的代码,唯一缺少的是:

thread.start();

我用过:

Log.d("result: ", builder.toString());

显示logcat中收到的JSON数据。