使用 Android HttpURLConnection 获取 Http

2022-01-15 00:00:00 android-emulator java android-internet

我是 Java 和 Android 开发的新手,我尝试创建一个简单的应用程序,该应用程序应该联系 Web 服务器并使用 http get 将一些数据添加到数据库中.

I'm new to Java and Android development and try to create a simple app which should contact a web server and add some data to a database using a http get.

当我使用计算机中的网络浏览器拨打电话时,它工作得很好.但是,当我在 Android 模拟器中运行应用程序时,不会添加任何数据.

When I do the call using the web browser in my computer it works just fine. However, when I do the call running the app in the Android emulator no data is added.

我已将 Internet 权限添加到应用的清单中.Logcat 没有报告任何问题.

I have added Internet permission to the app's manifest. Logcat does not report any problems.

谁能帮我找出问题所在?

Can anyone help me to figure out what's wrong?

这里是源代码:

package com.example.httptest;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class HttpTestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView tv = new TextView(this);
        setContentView(tv);

        try {
            URL url = new URL("http://www.mysite.se/index.asp?data=99");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.disconnect();
            tv.setText("Hello!");
        }
        catch (MalformedURLException ex) {
            Log.e("httptest",Log.getStackTraceString(ex)); 
        }
        catch (IOException ex) {
            Log.e("httptest",Log.getStackTraceString(ex));
        }   
    }        
}

推荐答案

尝试从这里获取输入流,然后可以得到文本数据:-

Try getting the input stream from this you can then get the text data as so:-

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://www.mysite.se/index.asp?data=99");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }    
    }

您也可以使用其他输入流阅读器,例如缓冲阅读器.

You can probably use other inputstream readers such as buffered reader also.

问题是当您打开连接时 - 它不会拉"任何数据.

The problem is that when you open the connection - it does not 'pull' any data.

相关文章