HTTP GET采用Android HttpURLConnection类 [英] Http Get using Android HttpURLConnection

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

问题描述

我是新来的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?

下面是源$ C ​​$ C:

Here is the source code:

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();
        }    
    }

您或许可以使用其他的InputStream读者如缓冲的读者也。

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.

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

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