android 同步http,android – 如何进行同步或异步HTTP Post / Get

这个博客示例展示了如何在Android应用中使用AsyncTask执行HTTP GET请求。通过创建一个DownloadTask类,该类继承自AsyncTask,可以在后台线程中下载网页内容,避免阻塞UI。在onPostExecute方法中,使用Toast显示请求结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在下面发布的示例基于我在Android Developer Docs上找到的示例.您可以找到示例

HERE,查看该示例以获得更全面的示例.

您将能够使用以下内容发出任何http请求

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 {

@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);

}

}

您可以使用代码来满足您的需求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值