[英]Android Intent send request to a link
如何在不使用浏览器打开请求的情况下将请求从应用程序发送到链接? 我尝试了Intent
But,但在浏览器中将其打开; “ Android”
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
如果要在浏览器中显示它,请使用以下代码
if (!url.startsWith("http://")
&& !url.startsWith("https://"))
url = "http://" + url;
browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
但是,如果您不想打开浏览器并在应用程序本身中显示它,则可以使用WebView。 在此链接上有一个很好的教程。
您可以使用普通的Java方法来完成此操作。
使用HttpURLConnection
,设置标题和内容并发送请求。
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set properties for con
// Set headers on this connection if required
// add url form parameters
DataOutputStream ostream = null;
try {
ostream = new DataOutputStream(con.getOutputStream());
String requestContents;
// Set the contents of the request
if (requestContents != null) {
// write the contents to the stream
ostream.writeBytes(requestContents);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ostream != null) {
ostream.flush();
ostream.close();
}
}
试试吧
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String link ="url";
DefaultHttpClient hc=new DefaultHttpClient();
ResponseHandler <String> res=new BasicResponseHandler();
HttpPost postMethod=new HttpPost(link);
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action","XYZ" ));
nameValuePairs.add(new BasicNameValuePair("udid","XYZ" ));
nameValuePairs.add(new BasicNameValuePair("user", "XYZ"));
try {
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response=hc.execute(postMethod,res);
System.out.println("response is== "+response);
Toast.makeText(this,response, Toast.LENGTH_SHORT);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
要执行此类:
new RequestTask().execute(insert your Http link );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.