如何进行同步或异步HTTP发布/获取 [英] How to make Sync or Async HTTP Post/Get

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

问题描述

我需要同步或异步HTTP Post / Get来从Web服务获取HTML数据。我搜索整个互联网,但我不能给出好结果。

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.

我试图使用这个例子:

  • Android Series get/post and multipost requests
  • Jcabi.com
  • Execute HTTP Post request in android

但它们对我没什么用。

HttpClient HttpGet 被淘汰,错误是:


org.apache.http.client.HttpClient已弃用

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

代码:

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


推荐答案

我在下面发布的示例基于我在 Android Developer Docs 上找到的示例。您可以在这里找到该示例,请查看更多信息综合示例。

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.

您可以使用以下内容发出任何http请求

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发布/获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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