如何使同步或异步HTTP POST /获取Android Studio中 [英] how make Sync or Async HTTP Post/Get in Android Studio

查看:340
本文介绍了如何使同步或异步HTTP POST /获取Android Studio中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android的编程初学者。我使用Android的工作室来开发一些简单的应用程序。

在这个时刻,我需要同步或异步HTTP POST / GET从Web服务获取的HTML数据。我这个搜索整个互联网,但我不能给好的结果。

我试图用这样的例子:

但没有他们为我工作。

的HttpClient HTTPGET 被划掉,错误是:


  

org.apache.http.client.HttpClient是德precated


code:

 尝试
{
    HttpClient的客户端=新DefaultHttpClient();
    字符串的getURL =google.com
    HTTPGET GET =新HTTPGET(的getURL);
    HTT presponse responseGet = client.execute(获取);
    HttpEntity resEntityGet = responseGet.getEntity();
    如果(resEntityGet!= NULL)
    {
        //做一些与响应
    }
}
赶上(例外五)
{
    e.printStackTrace();
}


解决方案

我已经贴在下面的例子是基于我的 Android开发者文档找到了一个例子。你可以发现,例如这里,看看那一个更COM prehensive例子。

您将能够作出任何HTTP请求具有以下

 进口android.app.Activity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.Toast;进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.io.Reader;
进口java.io.UnsupportedEncodingException;
进口java.net.HttpURLConnection中;
进口的java.net.URL;公共类MainActivity延伸活动{
    私有静态最后弦乐TAG = MainActivity.class.getSimpleName();    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        新DownloadTask()执行(http://www.google.com/);
    }    私有类DownloadTask扩展的AsyncTask<弦乐,太虚,字符串> {        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            //做在这里你的要求,这样你就不会中断UI线程
            尝试{
                返回downloadContent(PARAMS [0]);
            }赶上(IOException异常五){
                返回无法检索数据的URL可能是无效的。
            }
        }        @覆盖
        保护无效onPostExecute(字符串结果){
            //这里你的任务完成
            Toast.makeText(MainActivity.this,结果,Toast.LENGTH_LONG).show();
        }
    }    私人字符串downloadContent(字符串myurl)抛出IOException
        InputStream为= NULL;
        INT长度= 500;        尝试{
            网址URL =新的URL(myurl);
            HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
            conn.setReadTimeout(10000 / *毫秒* /);
            conn.setConnectTimeout(15000 / *毫秒* /);
            conn.setRequestMethod(GET);
            conn.setDoInput(真);
            conn.connect();
            INT响应= conn.getResponse code();
            Log.d(TAG的反应是:+响应);
            是= conn.getInputStream();            //将InputStream的成字符串
            字符串contentAsString = convertInputStreamToString(是,长度);
            返回contentAsString;
        } {最后
            如果(是!= NULL){
                is.close();
            }
        }
    }    公共字符串convertInputStreamToString(InputStream的流,INT长度)抛出IOException异常,UnsupportedEncodingException {
        读卡器读卡器= NULL;
        读者=新InputStreamReader的(流,UTF-8);
        的char []缓冲区=新的char [长度]
        reader.read(缓冲液);
        返回新的String(缓冲);
    }
}

您可以玩的code,以满足您的需求。

I'm beginner in Android programming. I'm using Android studio to develop some simple app.

At this moment I need Sync or Async HTTP Post/Get to get HTML data from Web-Service. I search this whole internet but I can't give good result.

I tried to use this examples:

but nothing of them working for me.

HttpClient and HttpGet is cross out, error is :

"org.apache.http.client.HttpClient is deprecated "

Code:

try
{
    HttpClient client = new DefaultHttpClient();
    String getURL = "google.com";
    HttpGet get = new HttpGet(getURL);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    if (resEntityGet != null)
    {
        //do something with the response 
    }
}
catch (Exception e)
{
    e.printStackTrace();
}

解决方案

The example I have posted below is based on an example that I found on the Android Developer Docs. You can find that example HERE, look at that for a more comprehensive example.

You will be able to make any http requests with the following

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();

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

        new DownloadTask().execute("http://www.google.com/");
    }

    private class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //do your request in here so that you don't interrupt the UI thread
            try {
                return downloadContent(params[0]);
            } catch (IOException e) {
                return "Unable to retrieve data. URL may be invalid.";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            //Here you are done with the task
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
        }
    }

    private String downloadContent(String myurl) throws IOException {
        InputStream is = null;
        int length = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();

            // Convert the InputStream into a string
            String contentAsString = convertInputStreamToString(is, length);
            return contentAsString;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[length];
        reader.read(buffer);
        return new String(buffer);
    }
}

You can play around with the code to suit your needs

这篇关于如何使同步或异步HTTP POST /获取Android Studio中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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