Android 如何进行同步或异步HTTP Post/Get
我需要同步或异步HTTP Post/Get从Web服务获取HTML数据。我搜索了整个互联网,但我不能给出好的结果 我尝试使用以下示例:Android 如何进行同步或异步HTTP Post/Get,android,http,Android,Http,我需要同步或异步HTTP Post/Get从Web服务获取HTML数据。我搜索了整个互联网,但我不能给出好的结果 我尝试使用以下示例: 但他们都不为我工作 HttpClient和HttpGet被划掉,错误为: “org.apache.http.client.HttpClient已弃用” 代码: try { HttpClient client = new DefaultHttpClient(); String getURL = "google.com"; Http
HttpClient
和HttpGet
被划掉,错误为:
“org.apache.http.client.HttpClient已弃用”
代码:
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开发者文档中找到的一个示例。你可以找到这个例子,看看这个更全面的例子 您将能够使用以下命令发出任何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<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);
}
}
导入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扩展了活动{
私有静态最终字符串标记=MainActivity.class.getSimpleName();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建下载任务()。执行(“http://www.google.com/");
}
私有类DownloadTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
//在这里执行请求,这样就不会中断UI线程
试一试{
返回下载内容(参数[0]);
}捕获(IOE异常){
return“无法检索数据。URL可能无效。”;
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
//在这里你完成了任务
Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG.show();
}
}
私有字符串下载内容(字符串myurl)引发IOException{
InputStream=null;
整数长度=500;
试一试{
URL=新URL(myurl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000/*毫秒*/);
conn.setConnectTimeout(15000/*毫秒*/);
conn.setRequestMethod(“GET”);
conn.setDoInput(真);
连接();
int response=conn.getResponseCode();
Log.d(标记“响应为:”+响应);
is=conn.getInputStream();
//将InputStream转换为字符串
字符串contentAsString=convertInputStreamToString(is,长度);
返回contentAsString;
}最后{
如果(is!=null){
is.close();
}
}
}
公共字符串convertInputStreamToString(InputStream,int-length)引发IOException,UnsupportedEncodingException{
Reader=null;
读卡器=新的InputStreamReader(流,“UTF-8”);
字符[]缓冲区=新字符[长度];
读(缓冲区);
返回新字符串(缓冲区);
}
}
您可以根据自己的需要使用代码您可以使用
这给了你所需要的一切。如果您决定使用AsyncTask并自己编写它,我建议不要在活动中使用AsyncTask,而是将它放在包装类中并使用回调函数。这将保持您的活动干净,并使网络代码可重用。这或多或少是他们在截击中所做的 **异步POST&GET请求**
**Async POST & GET request**
public class FetchFromServerTask extends AsyncTask<String, Void, String> {
private FetchFromServerUser user;
private int id;
public FetchFromServerTask(FetchFromServerUser user, int id) {
this.user = user;
this.id = id;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
user.onPreFetch();
}
@Override
protected String doInBackground(String... params) {
URL urlCould;
HttpURLConnection connection;
InputStream inputStream = null;
try {
String url = params[0];
urlCould = new URL(url);
connection = (HttpURLConnection) urlCould.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setRequestMethod("GET");
connection.connect();
inputStream = connection.getInputStream();
} catch (MalformedURLException MEx){
} catch (IOException IOEx){
Log.e("Utils", "HTTP failed to fetch data");
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
protected void onPostExecute(String string) {
//Do your own implementation
}
}
****---------------------------------------------------------------***
You can use GET request inn any class like this:
new FetchFromServerTask(this, 0).execute(/*Your url*/);
****---------------------------------------------------------------***
公共类FetchFromServerTask扩展了AsyncTask{
私有获取服务器用户;
私有int-id;
公共FetchFromServerTask(FetchFromServerUser用户,int id){
this.user=用户;
this.id=id;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
user.onPreFetch();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
URL可以;
httpurl连接;
InputStream InputStream=null;
试一试{
字符串url=params[0];
URLCOAN=新URL(URL);
connection=(HttpURLConnection)urlcoan.openConnection();
连接。设置连接超时(30000);
connection.setReadTimeout(30000);
connection.setRequestMethod(“GET”);
connection.connect();
inputStream=connection.getInputStream();
}捕获(格式不正确的异常MEx){
}捕获(IOException IOEx){
Log.e(“Utils”,“HTTP无法获取数据”);
返回null;
}
BufferedReader reader=新的BufferedReader(新的InputStreamReader(inputStream));
StringBuilder sb=新的StringBuilder();
弦线;
试一试{
而((line=reader.readLine())!=null){
sb.append(行)。append(“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
inputStream.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
受保护的void onPostExecute(字符串){
//做你自己的实现
}
}
****---------------------------------------------------------------***
您可以在以下任何类中使用GET请求:
新建FetchFromServerTask(此,0)。执行(/*您的url*/);
****---------------------------------------------------------------***
对于Post请求,只需更改:connection.setRequestMethod(“GET”);到
connection.setRequestMethod(“POST”) 可能是,如果您发布了尝试中的错误,可能会导致结果。我无法运行应用程序,因为HttpClient和HttpGet被划掉,错误为: