如何使用 HttpURLConnection 将 GET 请求与 Web API 一起用于 JSON 响应?

狼牙棒

过去几天,我一直试图从 Web API 获得成功的 JSON 调用,但没有成功。我尝试了多个 API 都没有成功,所以我认为这不是 API 本身,而是我如何使用 HttpURLConnection 调用它。

这是我的代码的修剪版本:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView textView = (TextView) findViewById(R.id.textView);
    String urlString = "http://ip.jsontest.com/";
    String jsonString = null;

    HttpURLConnection connection = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStream stream = connection.getInputStream();

        Scanner scan = new Scanner(stream).useDelimiter("\\A");

        jsonString = scan.next();
        scan.close();

        connection.disconnect();



    } catch (Exception e) { 
        e.printStackTrace();
    } 
    textView.setText(jsonString);

}}

我遵循并使用了多个教程和指南,试图使其正常工作,但无济于事。我还尝试使用 BufferedReader 和 StringBuilder 来提取数据,但无济于事。

编辑:

过去我也把它变成了一个单独的类,但没有成功:

public class NetworkConnect   {

/**
 * Execute the given URI, and return the data from that URI.
 *
 * @param uri the universal resource indicator for a set of data.
 * @return the set of data provided by the uri
 */

    private Exception exception;

    HttpURLConnection connection = null;
    BufferedReader reader = null;
    protected String doInBackground(String urlString) {
        try {

            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

            }

            return buffer.toString();


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
丹尼尔纽金特

只需使用 AsyncTask 子类即可在doInBackground()方法覆盖中执行网络操作,该方法在后台线程上运行。然后将结果传递给onPostExecute()在 UI 线程上运行方法覆盖。

这是一个带有 AsyncTask 的简单 Activity,可以执行您需要的操作:

public class TestActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        textView = (TextView) findViewById(R.id.textView);

        new NetworkConnect().execute();
    }

    class NetworkConnect extends AsyncTask<Void, Void, JSONObject> {

        private static final String JSON_URL = "http://ip.jsontest.com/";
        String charset = "UTF-8";
        HttpURLConnection conn;
        StringBuilder result;
        URL urlObj;

        @Override
        protected JSONObject doInBackground(Void... args) {

            JSONObject retObj = null;

            try {
                urlObj = new URL(JSON_URL);

                conn = (HttpURLConnection) urlObj.openConnection();
                conn.setDoOutput(false);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept-Charset", charset);
                conn.setConnectTimeout(15000);
                conn.connect();

                //Receive the response from the server
                InputStream in = new BufferedInputStream(conn.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                Log.d("NetworkConnect", "result: " + result.toString());

                retObj = new JSONObject(result.toString());

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

            return retObj;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            //Use JSON result to display in TextView
            if (json != null) {
                textView.setText(json.toString());
            }
        }
    }
}

注意:确保您在 AndroidManifest.xml 中拥有 INTERNET 权限:

<uses-permission android:name="android.permission.INTERNET" />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将Retrofit2与recyclerview一起用于嵌套JSON,响应不兼容

如何将Alamofire与自定义标头一起用于POST请求

将Python模块请求与Sitescout API一起使用时的响应状态代码400

使用HttpURLConnection执行POST请求时获取JSON响应

如何将 if/else 语句与 JSON fetch API 响应 Javascript 一起使用

将SAML与JWT一起用于Node API

将max与“ get”方法一起用于字典

在对JSON进行HTTP请求后,如何将angular-in-memory-web-api返回给Observable的响应变形?

如何将TLS / SSL Http身份验证与CXF客户端一起用于Web服务?

如何将IN运算符与Yii2REST Web服务的GET请求一起使用

如何使用Web Api实现请求/响应模式?

将Autofac配置为与ASP.NET MVC和ASP.NET Web Api一起用于现有应用程序

将axios.all与实例一起用于POST请求

如何使用文件流和 json 对象作为 Web API 的单一响应进行响应

如何从get请求中获取json响应而不是html响应?

将wc_get_product()与PHP变量一起用于产品ID

如何将常量值和api get请求一起发送到节点服务器

如何测试Web API JSON响应?

获取GET请求对API的响应

如何将Testcontainers Cassandra与Spring Data一起用于Apache Cassandra?

如何将INDIRECT与SUMIFS一起用于标准范围?

如何将packageScan和Persistence.xml一起用于EntityManagerFactory?

如何将asciidoctor与tocify一起用于动态toc?

如何将Nginx与Go一起用于子域?

我们如何将Typescript与CodeceptJS一起用于测试框架?

如何将Stanford CoreNLP Java库与Ruby一起用于情感分析?

如何将 vuex 与 Konva 一起用于 onDragEnd 选项

如何将Launchmyapp与Meteor一起用于验证电子邮件链接?

如何将curl与:: 1一起用于基于ipv6的环回?