如果您对http://www.android.com/不用fq了和再也不用安卓感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解http://www.android.com/不用fq了的各种细节,
如果您对http://www.android.com/不用fq了和再也不用安卓感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解http://www.android.com/不用fq了的各种细节,并对再也不用安卓进行深入的分析,此外还有关于Android Studio:ping URL 时出错:http://google.com不允许到 google.com 的明文 HTTP 流量、Android 开发进阶(四)-- 深入 Android 通过 Apache HTTP 访问 HTTP 资源、Android 网络请求框架 android-async-http 的一个细节问题(org.apache.http.client.CircularRedirectException 异常)、Cordova ajax http 请求失败的解决方法,xcode 7 更新 plist 支持 http的实用技巧。
本文目录一览:- http://www.android.com/不用fq了(再也不用安卓)
- Android Studio:ping URL 时出错:http://google.com不允许到 google.com 的明文 HTTP 流量
- Android 开发进阶(四)-- 深入 Android 通过 Apache HTTP 访问 HTTP 资源
- Android 网络请求框架 android-async-http 的一个细节问题(org.apache.http.client.CircularRedirectException 异常)
- Cordova ajax http 请求失败的解决方法,xcode 7 更新 plist 支持 http
http://www.android.com/不用fq了(再也不用安卓)
如题Android Studio:ping URL 时出错:http://google.com不允许到 google.com 的明文 HTTP 流量
如何解决Android Studio:ping URL 时出错:http://google.com不允许到 google.com 的明文 HTTP 流量
我正在使用 Facebook Audience Network
AdMob
测试 mediation
广告。我正在使用他们文档中提到的 Mediation Test Suite
对其进行测试。
当我尝试从中介测试套件中的 facebook 广告加载广告时出现此错误(从 admob 加载广告工作正常)。
Error while pinging URL: http://google.com. Cleartext HTTP traffic to google.com not permitted
Ad Failed to load : 0
SO 中提出了很多类似的问题,但没有一个对我有用。
这与 Network security configuration
有关。根据他们的文档,我在我的应用程序中添加了所有必要的文件。它们是:
res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">127.0.0.1</domain>
</domain-config>
</network-security-config>
AndroidManifest.xml
<application
...
android:networkSecurityConfig="@xml/network_security_config">
...
</application>
我也试过在清单文件中使用 android:usesCleartextTraffic="true"
但后来我得到这个错误:
Ad Failed to load : 0
Received non-success response code 302 from pinging URL: http://google.com
我已经按照 SO 上的一些答案中的建议卸载并安装了我的应用,但仍然无法正常工作。
我该如何解决这个问题?
Android 开发进阶(四)-- 深入 Android 通过 Apache HTTP 访问 HTTP 资源
深入 Android 通过 Apache HTTP 访问 HTTP 资源
HttpClient 接口
实现类:DefaultHttpClient 这也是常用的一个用于实现 HttpClient 接口的子类,
HttpClietnt 中定义的常用抽象方法
方法名称
描述
public abstract HttpResponse execute (HttpUriRequest request)
通过 HttpUriRequest 对象执行返回一个 HttpResponse 对象
public abstract HttpResponse execute (HttpUriRequest request, HttpContext context)
通过 HttpUriRequest 对象和 HttpContext 对象执行返回一个 HttpResponse 对象
HttpResponse 接口
HttpResponse 接口里定义了一系列的 set、get 方法
方法名称
描述
public abstract HttpEntity getEntity ()
得到一个 HttpEntity 对象
public abstract StatusLine getStatusLine ()
得到一个 StatusLine(也就是 HTTP 协议中的状态行我们知道 HTPP 状态行由三部分组成:HTTP 协议版本,服务器发回的响应状态代码,状态码的文本描述)接口的实例对象
public abstract Locale getLocale ()
得到 Locale 对象
…. 相应的 set 方法
StatusLine 接口
StatusLine 接口的常用方法。也可以通过其实现的子类 BasicStatusLine 类里查看
方法名称
描述
public abstract ProtocolVersion getProtocolVersion ()
得到一个 ProtolVersion 对象它是一个 HTTP 版本的封装类,在这个类里定义了一系列的方法我们可以通过它的 getProtocol 方法取得协议名称,getMinor 得到 HTPP 协议的版本
public abstract String getReasonPhrase ()
状态码的文本描述
public abstract int getStatusCode ()
得到响应状态码
HttpEntity 接口
HttpEntity 是一个接口
方法名称
描述
public abstract InputStream getContent ()
得到一个输入流对象,我们可以用这个流来操作文件(例如保存文件到 SD 卡)
public abstract Header getContentType ()
得到 Content-Type 信息头
public abstract Header getContentEncoding ()
得到 Content-Encoding 信息头
我们可以通过 EntityUtils 类,它是一个 final 类,一个专门针对于处理 HttpEntity 的帮助类
常用方法
EntityUtils 类
EntityUtils 类的常用方法
方法名称
描述
public static String getContentCharSet (HttpEntity entity)
设置 HttpEntity 对象的 ContentCharset
public static byte[] toByteArray (HttpEntity entity)
将 HttpClient 转换成一个字节数组
public static String toString (HttpEntity entity, String defaultCharset)
通过指定的编码方式取得 HttpEntity 里字符串内容
public static String toString (HttpEntity entity)
取得 HttpEntity 里字符串内容
NameValuePair
NameValuePair 接口是一个简单的封闭的键值对,只提供了一个 getName () 和一个 getValue 方法。主要用到的实现类 BasicNameVaulePair
HttpGet 类
HttpGet 它实现了 HttpRequest、HttpUriRequest 接口
构造方法
方法名称
描述
public HttpGet ()
无参数构造方法用以实例化对象
public HttpGet (URI uri)
通过 URI 对象构造 HttpGet 对象
public HttpGet (String uri)
通过指定的 uri 字符串地址构造实例化 HttpGet 对象
HttpPost 类
同样它也实现了 HttpRequest、HttpUriRequest 接口等一系列接口
构造方法
方法名称
描述
public HttpPost ()
无参数构造方法用以实例化对象
public HttpPost (URI uri)
通过 URI 对象构造 HttpPost 对象
public HttpPost (String uri)
通过指定的 uri 字符串地址构造实例化 HttpPost 对象
清楚了上面的所有常用 API 后,下面我们能过 Apache HTTP 来访问 HTTP 资源
三步曲:
1. 创建 HttpGet 或者 HttpPost 对象,将要请求的 URL 对象构造方法传入 HttpGet、HttpPost 对象
2. 通过 HttpClent 接口的实现类 DefaultClent. 的 excute (HttpUriRequest request) 而我们已经知道 HttpGet 和 HttpPost 类都实现了 HttpUriRequest 接口,所以这里面,我们可以将第 1 步创建好的 HttpGet 或者 HttpPost 对象传入进来。来得到 HttpResponse 对象
3. 通过 HttpResponse 取到返回的一些信息,再做提取
实例图片:
帖上一部分源代码:
布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content">
- <TextView android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="url:" />
- <EditText android:id="@+id/urlText" android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="http://10.0.2.2:8080/NetServer/queryServlet?bookId=2" />
- </LinearLayout>
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:gravity="right">
- <Button android:id="@+id/getBtn" android:text="GET 请求"
- android:layout_width="wrap_content" android:layout_height="wrap_content" />
- <Button android:id="@+id/postBtn" android:text="POST 请求"
- android:layout_width="wrap_content" android:layout_height="wrap_content" />
- </LinearLayout>
- <TextView android:id="@+id/resultView" android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content">
- <TextView android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="图片 url:" />
- <EditText android:id="@+id/imageurlText" android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:text="http://hiphotos.baidu.com/censhenlu/pic/item/3982b502915ddf9c7a8947c3.jpg" />
- </LinearLayout>
- <Button android:id="@+id/imgBtn" android:text="获取图片"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:layout_gravity="right" />
- <ImageView android:id="@+id/imgeView01"
- android:layout_height="wrap_content" android:layout_width="fill_parent" />
- </LinearLayout>
Java 代码:
- package com.jiahui.net;
- import java.io.InputStream;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.StatusLine;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ImageButton;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- public class HTTPDemoActivity extends Activity {
- private Button getBtn, postBtn, imageBtn;
- private EditText urlText, imageUrlText;
- private TextView resutlView;
- private ImageView imageView;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- urlText = (EditText) findViewById(R.id.urlText);
- imageUrlText = (EditText) findViewById(R.id.imageurlText);
- resutlView = (TextView) findViewById(R.id.resultView);
- getBtn = (Button) findViewById(R.id.getBtn);
- postBtn = (Button) findViewById(R.id.postBtn);
- imageBtn = (Button) findViewById(R.id.imgBtn);
- imageView = (ImageView) findViewById(R.id.imgeView01);
- getBtn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- System.out.println(urlText.getText().toString());
- resutlView
- .setText(request("GET", urlText.getText().toString()));
- }
- });
- postBtn.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- System.out.println(urlText.getText().toString());
- resutlView
- .setText(request("POST", urlText.getText().toString()));
- }
- });
- imageBtn.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- getImage(imageUrlText.getText().toString());
- }
- });
- }
- private String request(String method, String url) {
- HttpResponse httpResponse = null;
- StringBuffer result = new StringBuffer();
- try {
- if (method.equals("GET")) {
- // 1. 通过 url 创建 HttpGet 对象
- HttpGet httpGet = new HttpGet(url);
- // 2. 通过 DefaultClient 的 excute 方法执行返回一个 HttpResponse 对象
- HttpClient httpClient = new DefaultHttpClient();
- httpResponse = httpClient.execute(httpGet);
- // 3. 取得相关信息
- // 取得 HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 得到一些数据
- // 通过 EntityUtils 并指定编码方式取到返回的数据
- result.append(EntityUtils.toString(httpEntity, "utf-8"));
- // 得到 StatusLine 接口对象
- StatusLine statusLine = httpResponse.getStatusLine();
- // 得到协议
- ;
- result.append("协议:" + statusLine.getProtocolVersion() + "\r\n");
- int statusCode = statusLine.getStatusCode();
- result.append("状态码:" + statusCode + "\r\n");
- } else if (method.equals("POST")) {
- // 1. 通过 url 创建 HttpGet 对象
- HttpPost httpPost = new HttpPost(url);
- // 2. 通过 DefaultClient 的 excute 方法执行返回一个 HttpResponse 对象
- HttpClient httpClient = new DefaultHttpClient();
- httpResponse = httpClient.execute(httpPost);
- // 3. 取得相关信息
- // 取得 HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 得到一些数据
- // 通过 EntityUtils 并指定编码方式取到返回的数据
- result.append(EntityUtils.toString(httpEntity, "utf-8"));
- StatusLine statusLine = httpResponse.getStatusLine();
- statusLine.getProtocolVersion();
- int statusCode = statusLine.getStatusCode();
- result.append("状态码:" + statusCode + "\r\n");
- }
- } catch (Exception e) {
- Toast.makeText(HTTPDemoActivity.this, "网络连接异常", Toast.LENGTH_LONG)
- .show();
- }
- return result.toString();
- }
- public void getImage(String url) {
- try {
- // 1. 通过 url 创建 HttpGet 对象
- HttpGet httpGet = new HttpGet(url);
- // 2. 通过 DefaultClient 的 excute 方法执行返回一个 HttpResponse 对象
- HttpClient httpClient = new DefaultHttpClient();
- HttpResponse httpResponse = httpClient.execute(httpGet);
- // 3. 取得相关信息
- // 取得 HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 4. 通过 HttpEntiy.getContent 得到一个输入流
- InputStream inputStream = httpEntity.getContent();
- System.out.println(inputStream.available());
- // 通过传入的流再通过 Bitmap 工厂创建一个 Bitmap
- Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
- // 设置 imageView
- imageView.setImageBitmap(bitmap);
- } catch (Exception e) {
- Toast.makeText(HTTPDemoActivity.this, "网络连接异常", Toast.LENGTH_LONG)
- .show();
- }
- }
- }
开发注意事项:
1.要想访问本地机器不能写成 localhost 或者 127.0.0.1 要写成 10.0.2.2。这是因为 Android 模拟器 (simulator) 把它自己作为了 localhost,也就是说,代码中使用 localhost 或者 127.0.0.1 来访问,都是访问模拟器自己!若你想在模拟器 simulator 上面访问你的电脑,那么就使用 android 内置的 IP: 10.0.2.2,10.0.2.2 是模拟器设定的特定 ip, 是你电脑的别名,在模拟器上用 10.0.2.2 就能成功访问你的电脑本机。
2.记得加上网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
源代码下载:http://download.csdn.net/detail/jiahui524/3690598
Android 网络请求框架 android-async-http 的一个细节问题(org.apache.http.client.CircularRedirectException 异常)
今天通过接口请求服务器的一些 app 数据,发现一个很奇怪的问题,请求一个链接的时候,通常在第一次请求发起的时候没有什么问题,能很快的拿到数据,但是往后再去请求的时候就会等待很久,而且最后会请求失败,一直找不到原因所在,最后查看 log 发现这个请求抛出了一个异常:
org.apache.http.client.CircularRedirectException
详细的异常信息如下图:
其实异常信息很明显,是链接重定向的问题,按道理应该是服务器的问题,至于服务器怎么去改,明天问下同事,不是很明白这一块;
网络请求用的是 Android 的一个网络请求框架:android-async-http;
找了些资料,客户端请求这边也可以解决这个问题,在发起的请求的时候,给 httpclient 设置参数,如下:
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
ok,问题解决,去逛逛淘宝,往购物车加点东西,但就不买单
Cordova ajax http 请求失败的解决方法,xcode 7 更新 plist 支持 http
记录下 Cordova ajax http 请求的折腾纪录
尝试 Cordova 也就是 phonegap 做 App ,尝试 http 请求。遇到请求失败的几处需要注意修改的地方。
- Cordova 自带的 demo 的 meta 标记限制了行内 javascript 和 http 请求的域名范围。如下改为无限制。
<!-- <meta http-equiv="Content-Security-Policy" content="default-src ''self'' ''unsafe-inline'' data: gap: https://ssl.gstatic.com ''unsafe-eval''; style-src ''self'' ''unsafe-inline''; media-src *">-->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src ''self'' ''unsafe-inline''; script-src ''self'' ''unsafe-inline'' ''unsafe-eval''">
-
config.xml 需要设置为 <access origin="*" /> 或者自己的服务器域名
-
xcode 更新了网络请求的安全限制,默认强制要求 https 了。解决办法是在 plist 文件里添加自定义的配置。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
demo 代码
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html>
<head>
<!--
Customize this policy to fit your own app''s needs. For more guidance, see:
https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
Some notes:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add ''unsafe-inline'' to default-src
-->
<!-- <meta http-equiv="Content-Security-Policy" content="default-src ''self'' ''unsafe-inline'' data: gap: https://ssl.gstatic.com ''unsafe-eval''; style-src ''self'' ''unsafe-inline''; media-src *">-->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src ''self'' ''unsafe-inline''; script-src ''self'' ''unsafe-inline'' ''unsafe-eval''">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1 id="headline">Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<input type="text" id="url">
<input type="button" onclick="httpGet();" value="button">
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// ''load'', ''deviceready'', ''offline'', and ''online''.
bindEvents: function() {
document.addEventListener(''deviceready'', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of ''this'' is the event. In order to call the ''receivedEvent''
// function, we must explicitly call ''app.receivedEvent(...);''
onDeviceReady: function() {
app.receivedEvent(''deviceready'');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector(''.listening'');
var receivedElement = parentElement.querySelector(''.received'');
listeningElement.setAttribute(''style'', ''display:none;'');
receivedElement.setAttribute(''style'', ''display:block;'');
console.log(''Received Event: '' + id);
}
};
app.initialize();
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
//console.log(navigator.contacts);
$(''#url'').val(''test.html'');
}
function httpGet(){
var url = $(''#url'').val();
$.ajax({
type : "GET",
url : url,
crossDomain: true,
//beforeSend : function() {$.mobile.loading(''show'')},
//complete : function() {$.mobile.loading(''hide'')},
//data : {username : ''subin'', password : ''passwordx''},
dataType : ''text'',
success : function(response) {
console.error(response);
alert(''Works!'');
},
error : function() {
//console.error("error");
alert(''Not working!'');
}
});
}
关于http://www.android.com/不用fq了和再也不用安卓的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Android Studio:ping URL 时出错:http://google.com不允许到 google.com 的明文 HTTP 流量、Android 开发进阶(四)-- 深入 Android 通过 Apache HTTP 访问 HTTP 资源、Android 网络请求框架 android-async-http 的一个细节问题(org.apache.http.client.CircularRedirectException 异常)、Cordova ajax http 请求失败的解决方法,xcode 7 更新 plist 支持 http的相关信息,请在本站寻找。
本文标签: