我需要同步或异步HTTP Post / Get来从Web服务获取HTML数据。我搜索整个互联网,但我不能给出好的结果。
我尝试使用这个例子:
但他们没有为我工作。
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();
}
答案 0 :(得分:8)
我在下面发布的示例基于我在 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<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);
}
}
您可以使用代码来满足您的需求
答案 1 :(得分:3)
您可以使用Volley 它为您提供所需的一切。如果您决定使用AsyncTask并自行编程,我建议您不要在Activity中使用AsyncTask,而是将其放在包装类中并使用回调函数。这样可以保持活动清洁并使网络代码可重用。这或多或少是他们在Volley中所做的。
答案 2 :(得分:0)
**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*/);
****---------------------------------------------------------------***
对于Post请求,只需更改:connection.setRequestMethod(&#34; GET&#34;);到
connection.setRequestMethod(&#34; POST&#34);