从Android URL获取HTML
在我的应用程序中,我希望从url显示html: 我尝试使用以下代码:从Android URL获取HTML,android,Android,在我的应用程序中,我希望从url显示html: 我尝试使用以下代码: public class MainActivity extends ActionBarActivity { TextView tv1, tv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView
public class MainActivity extends ActionBarActivity {
TextView tv1, tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000); // 3s max for connection
HttpConnectionParams.setSoTimeout(httpParameters, 4000); // 4s max to get data
HttpClient httpclient = new DefaultHttpClient(httpParameters); // Create HTTP Client
HttpGet httpget = new HttpGet("https://translate.google.com/?hl=vi#en/vi/hello"); // Set the action you want to do
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
Log.d("VD",resString);
is.close(); // Close the stream
//You can also add some params to the HttpClient to manage timeout and other stuff like that. Ex :
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我补充说:
<uses-permission android:name="android.permission.INTERNET" />
但它不起作用。如果您只需要获取值的值,请检查响应中的状态代码……它应该是200
int status=response.getStatusLine().getStatusCode();
if(status==200)
{
//Write your try catch code here
}
如果不是200,则问题来自链接响应