使用Android HttpURLConnection 获取Http [英] Http Get using Android HttpURLConnection

查看:41
本文介绍了使用Android HttpURLConnection 获取Http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 和 Android 开发的新手,尝试创建一个简单的应用程序,该应用程序应该联系网络服务器并使用 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.

这篇关于使用Android HttpURLConnection 获取Http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆