连接到远程服务器Android应用程序 [英] Android Application that connects to remote server

查看:119
本文介绍了连接到远程服务器Android应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对平台升级Froyo 2.2建立一个Android应用程序。该应用程序应该连接到远程服务器,从中获取数据并显示用户在不同的语言。


  • 所以我的问题 - 我需要什么样的技术学习,这样我就可以
    建立上述应用程序。

请注意 - 我已经安装了Android平台,并建立了简单的应用的Hello,world。我知道的Java。另外,我使用Eclipse。

感谢您的答案。没有粗鲁的评论,请...

// -------------- code使用HTTP协议连接到网络----------------- //

 包in.androidbook.Networking;进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口java.net.URLConnection中;进口javax.xml.parsers.DocumentBuilder中;
进口javax.xml.parsers.DocumentBuilderFactory中;
进口javax.xml.parsers.ParserConfigurationException;进口org.w3c.dom.Document中;
进口org.w3c.dom.Element中;
进口org.w3c.dom.Node中;
进口org.w3c.dom.NodeList;进口android.app.Activity;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.widget.ImageView;
进口android.widget.Toast;公共类MainActivity扩展活动
{
    ImageView的IMG;
    / *这是使异步调用,以确保连接到服务器将不会返回,直到接收到的数据* /    私有类BackgroundTask扩展的AsyncTask<弦乐,太虚,位图>
    {
        保护位图doInBackground(字符串... URL)
        {
            位图位图= DownloadImage(URL [0]);
            返回位图;
        }        保护无效onPostExecute(位图位图)
        {
            ImageView的IMG =(ImageView的)findViewById(R.id.img);
            img.setImageBitmap(位图);
        }
    }
    // code制作的HTTP连接
    私人的InputStream OpenHttpConnection(字符串urlString)抛出IOException异常
    {
        在的InputStream = NULL;
        INT响应= -1;        网址URL =新的URL(urlString); //我们以类URL的对象
        康涅狄格州的URLConnection = url.openConnection(); //创建一个连接对象,并打开连接        如果抛出新IOException异常(不是HTTP连接)((康涅狄格州的instanceof HttpURLConnection类)!);
        尝试
        {
            HttpURLConnection的httpConn =(HttpURLConnection类)美国康涅狄格州; // httpConn对象分配康恩的值。类型转换做是为了避免冲突。
            httpConn.setAllowUserInteraction(假);
            httpConn.setInstanceFollowRedirects(真);
            httpConn.setRequestMethod(GET);
            httpConn.connect();
            响应= httpConn.getResponse code();            如果(响应== HttpURLConnection.HTTP_OK)
                在= httpConn.getInputStream();
        }
        赶上(异常前)
        {
            抛出新IOException异常(错误连接);
        }
        返回;
    }
        // ------------------------------------------ OpenHttpConnection方法完成--- -------------------------------------------------- ----- //
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------//
    // -------------------------------方法下载图像------------ -------------------------------------------------- ------------------------ //
    私人位图DownloadImage(字符串URL)
    {
        位图位图= NULL;
        在的InputStream = NULL;
        尝试
        {
            在= OpenHttpConnection(URL);
            位= BitmapFactory.de codeStream(中);
            附寄();
        }
        赶上(IOException异常E1)
        {
            Toast.makeText(这一点,e1.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            //吐司显示一条短给用户的消息。这指的是当前对象。
            e1.printStackTrace();
        }
        返回位图;
    }
/ **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);       位图的位图= DownloadImage(http://i.zdnet.com/blogs/3-29-androids.jpg);
        IMG =(ImageView的)findViewById(R.id.img);
        img.setImageBitmap(位图);
    }
}


解决方案

已更新(基于评论):当我们谈论的是客户端,我确认我的答案。如果该网站是不是你的,你需要做的,如果检查有/如果它允许对某些类型的通信通过API,以及在什么样的格式(XML和JSON是最常用的)的第一件事。有了这个信息,它应该是pretty容易。看看使用谷歌地图或Twitter Android的例子,你应该找到一些。

嗯,这取决于你是什么意思正是:你要求需要在客户端(APP)的技能 - 服务器已经内置的想法,或将是别人的,或者所需要的技能服务器?

在前者的情况下,我会建议使用REST API和JSON沟通。看看阿帕奇HTTPGET,和的HTTPClient HTT presponse类org.json(全部都包含在Android设备)。如果你想与他们进行测试,使用一些公共API(所以你不必担心服务器),如谷歌地图API(这是简单,并且免费下一些限制使用)。

在后一种情况下,我与ColWinters:如果你知道的Java,用它也有与Tomcat作为服务器和基本的servlet。你会发现的例子在互联网上层层叠叠。

I am trying to build an Android App on Platform 2.2 Froyo. The app is supposed to connect to a remote server, fetch data from it and display to user in a different language.

  • So my question - What technologies I need to learn so that I can build the above app.

Note - I have already installed the Android platform and have built simple apps like Hello, world. I know Java. Also I am using Eclipse.

Thank you for your answers. No rude comment please...

//--------------Code for connecting to web using HTTP protocol-----------------//

package in.androidbook.Networking;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity 
{
    ImageView img;
    /* This is for making asynchronous calls to ensure that connection to server will not return until data is received */

    private class BackgroundTask extends AsyncTask<String, Void, Bitmap>
    {
        protected Bitmap doInBackground(String...url)
        {
            Bitmap bitmap = DownloadImage(url[0]);
            return bitmap;
        }

        protected void onPostExecute(Bitmap bitmap)
        {
            ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageBitmap(bitmap);         
        }
    }
    // Code for making HTTP connection
    private InputStream OpenHttpConnection(String urlString) throws IOException 
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);//We take an object of class URL
        URLConnection conn = url.openConnection(); //Create a connection object and open the connection

        if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http connection");
        try
        {
            HttpURLConnection httpConn = (HttpURLConnection) conn; //httpConn object is assigned the value of conn. Typecasting is done to avoid conflict.
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();

            if(response == HttpURLConnection.HTTP_OK)
                in = httpConn.getInputStream();
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");
        }
        return in;
    }   
        //------------------------------------------ OpenHttpConnection method completed----------------------------------------------------------//
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------//
    //-------------------------------Method to download an image--------------------------------------------------------------------------------------//
    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        try
        {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException e1)
        {
            Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            //Toast displays a short msg to user. this refers to current object.
            e1.printStackTrace();
        }
        return bitmap;
    }  


/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       Bitmap bitmap = DownloadImage("http://i.zdnet.com/blogs/3-29-androids.jpg");
        img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(bitmap);
    }
}

解决方案

UPDATED (based on comment) : As we are talking about the client side, I confirm my answer. If the site is not yours, the first thing you need to do if check how/if it allows for some kind of communication via API, and in what kind of format (XML and JSON being the most used). With this information, it should be pretty easy. Take a look of the Android example using the Google Map or Twitter, you should find some.

Well, it depends what do you mean exactly : are you asking for the skills needed on the client side (the app) - in the idea that the server is already built, or will be by someone else, or the skills needed for the server ?

In the former case, I would advice to communicate with REST API and JSON. Take a look at apache HTTPGet, HTTPClient and HTTPResponse class and org.json (all are included in Android). If you want to test with them, use some public APIs (so you do not have to worry about the server), such as Google Map API (which is simple and free to use under some limits).

In the latter case, I'm with ColWinters : if you know java, use it there also, with Tomcat as a server and a basic Servlet. You'll find examples aplenty on the Internet.

这篇关于连接到远程服务器Android应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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