java.IOException: Target host must not be null, or set in parameters. scheme=null, host=null, path=
网上查找各种资料,大多数都是说 Target host must not be null, 这个错误要么是URL开头没有加http:// 要么就URL是有非法字符的说法,但是我这边检查了很多次, URL完全符合访问要求,pc浏览器试过,然后手机自带的浏览器也可以访问,所以问题重点就出现在 or set in parameters。scheme = null,host = null,path = / guard /; jsessionid = AE0C1D08BE0EC9824E18510FA6FDF969 简单明了就是没有配置sessionid 也就是 cookieStore
BUG出现环境:
由于业务需求,app有一个对设备升级的功能,需要连续访问后台返回给的2个URL,一个是登录的URL,一个是下载的URL,按照写后台的程序猿所说,我先是访问登录的URL ,然后返回成功后再访问下载的URL,可是不管用什么方法,都访问不了下载的URL,会报如标题的错误,
为了测试下载工具类的下载方法是否奏效,我访问了网络上其他的下载URL,结果发现是可以下载的,这说明我的下载方法没有问题,那么网络上其他的下载URL和我的下载URL的区别就出来了,问题也就知道在哪了,我们需要访问登录的URL后才能访问下载URL! 但是登录后,再次访问下载的URL地址时需要设置sessionid,也就是cookieStore才能正常下载,
楼主的解决方法:
这里用到了xutils.jar包里面的下载工具 点击这里下载xUtils-2.6.14.jar
在下载()方法执行之前需要设置cookieStore,才能访问登陆过的下载URL访问登录的时候,就需要拿到cookie
/* 验证 *//*** * @Description:获取网络数据* @param jsonElement* 参数* @param url 访问地址* @param @return* @return String*/public static String httpPostJson(JsonElement jsonElement, String url) {String result = "";try {// 创建连/* 建立HTTP Post联机 */HttpClient httpClient = new DefaultHttpClient();HttpPost post = new HttpPost(url);post.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);post.setEntity(new StringEntity(jsonElement.toString(), HTTP.UTF_8));// 发送HttpPost请求,并返回HttpResponse对象HttpResponse httpResponse = httpClient.execute(post);// 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求if (httpResponse.getStatusLine().getStatusCode() == 200) {// 获取返回结果result = EntityUtils.toString(httpResponse.getEntity());// 获取cookie MyCookieStore.cookieStore = ((DefaultHttpClient) httpClient).getCookieStore();}} catch (Exception e) {e.printStackTrace();return null;}return result;}
拿到cookieStore后存到MyCookieStore类里面,然后直接拿出来用
import com.lidroid.xutils.http.HttpHandler;private HttpHandler<File> mDownLoadHelper;mDownLoadHelper = new HttpUtils().configCookieStore(MyCookieStore.cookieStore).download(apkUrl, cachePath, true, false, new RequestCallBack<File>()
关键代码:配置这个就不会报错了,
configCookieStore(MyCookieStore.cookieStore)
附上:MyCookieStore类,
package com.bluetoothunlocknew.ui.licenseKey.lockVersionUpgrade;import org.apache.http.client.CookieStore;/*** 登录后缓存的cookie, 用于网络请求下载文件* Created by Administrator on 2018/8/29.*/
public class MyCookieStore {public static CookieStore cookieStore=null;}
附上源码:
//下载升级包操作,下载完成后会发送广播Intent mIntent = new Intent();Bundle bundle = new Bundle();bundle.putString("apkUrl", downloadUrl);mIntent.setClass(this, DownloadApkService.class);mIntent.putExtras(bundle);startService(mIntent);
// 注册接收服务registerReceiver(new String[] { ConstantsUtil.UPDATE_RECEIVED_ACTION });
/*** 接收广播*/@Overrideprotected void handleReceiver(Context context, Intent intent) {//常量类 public static final String UPDATE_RECEIVED_ACTION = "UPDATE_RECEIVED_ACTION";if (intent.getAction().equals(ConstantsUtil.UPDATE_RECEIVED_ACTION)) {//succee do something}//常量类 public static final String UPDATE_ERROR = "UPDATE_ERROR";if (intent.getAction().equals(ConstantsUtil.UPDATE_ERROR)) { //error}}
import java.io.File;
import java.text.DecimalFormat;import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;import com.bluetoothunlocknew.R;
import com.bluetoothunlocknew.app.InitApplication;
import com.bluetoothunlocknew.utils.ConstantsUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;/*** * @ClassName: DownloadApkService* @Description: 下载最新Apk文件服务工具类,通知栏显示进度,下载完成震动提示,**/
public class DownloadApkService extends Service {private final int NotificationID = 0x10000;private NotificationManager mNotificationManager = null;private Notification.Builder builder;private HttpHandler<File> mDownLoadHelper;/*** Title: onBind* @Description:* @param intent* @return* @see Service#onBind(Intent)*/@Overridepublic IBinder onBind(Intent intent) {return null;}/*** Title: onCreate* @Description:* @see Service#onCreate()*/@Overridepublic void onCreate() {super.onCreate();}/*** Title: onStartCommand* @Description:* @param intent* @param flags* @param startId* @return* @see Service#onStartCommand(Intent, int, int)*/@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("onStartCommand");// 接收Intent传来的参数:Bundle bundle = intent.getExtras();String apkUrl = bundle.getString("apkUrl");
// String versionName = bundle.getString("versionName");downloadApk(apkUrl/*, versionName*/);// return super.onStartCommand(intent, flags, startId);return START_REDELIVER_INTENT;}// 下载配置文件private void downloadApk(final String apkUrl/*, String versionName*/) {// 创建保存路径File filePath = new File(InitApplication.SdCardFilePath + "/BlueToothUnlockNew/DownloadFile/", apkUrl.substring(apkUrl.lastIndexOf("/") + 1, apkUrl.length()));final String cachePath = filePath.getAbsolutePath();// 第一个参数fileUrl:文件url。// 第二个参数filePath:SD卡目标文件。// 第三个参数true: 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。// 第四个参数false: 如果从请求返回信息中获取到文件名,下载完成后自动重命名。mDownLoadHelper = new HttpUtils().configCookieStore(MyCookieStore.cookieStore).download(apkUrl, cachePath, true, false, new RequestCallBack<File>() {@Overridepublic void onStart() {super.onStart();System.out.println("开始下载文件");System.out.println(apkUrl);System.out.println(cachePath);mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);builder = new Notification.Builder(getApplicationContext());builder.setSmallIcon(R.drawable.app_logo);builder.setTicker("正在下载无线管理");builder.setContentText("正在下载,请稍后...");builder.setNumber(0);builder.setAutoCancel(true);mNotificationManager.notify(NotificationID, builder.build());}@Overridepublic void onLoading(long total, long current, boolean isUploading) {super.onLoading(total, current, isUploading);System.out.println("文件下载中");int x = Long.valueOf(current).intValue();int totalS = Long.valueOf(total).intValue();builder.setProgress(totalS, x, false);builder.setContentInfo(getPercent(x, totalS));mNotificationManager.notify(NotificationID, builder.build());}@Overridepublic void onSuccess(ResponseInfo<File> responseInfo) {System.out.println("文件下载完成");mNotificationManager.notify(NotificationID, builder.build());// 震动提示Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);vibrator.vibrate(1000L);// 参数是震动时间(long类型)stopSelf();mNotificationManager.cancel(NotificationID);// 发送广播至主界面安装apkIntent intent = new Intent(ConstantsUtil.UPDATE_RECEIVED_ACTION);intent.putExtra("filePath", cachePath);sendBroadcast(intent);}@Overridepublic void onFailure(HttpException error, String msg) {System.out.println("文件下载失败");System.out.println(error);System.out.println(msg);// 发送广播至主界面安装apkIntent intent = new Intent(ConstantsUtil.UPDATE_ERROR);intent.putExtra("error", "文件下载失败");sendBroadcast(intent);mNotificationManager.cancel(NotificationID);}@Overridepublic void onCancelled() {super.onCancelled();System.out.println("文件下载结束,停止下载器");mDownLoadHelper.cancel();}});}/*** * @param x* 当前值* @param total* 总值* @return 当前百分比* @Description:返回百分之值*/private String getPercent(int x, int total) {String result = "";// 接受百分比的值double x_double = x * 1.0;double tempresult = x_double / total;// 百分比格式,后面不足2位的用0补齐 ##.00%DecimalFormat df1 = new DecimalFormat("0.00%");result = df1.format(tempresult);return result;}/*** Title: onDestroy* @Description:* @see Service#onDestroy()*/@Overridepublic void onDestroy() {super.onDestroy();MyCookieStore.cookieStore = null; //清除cookie缓存stopSelf();}}
java.IOException: Target host must not be null, or set in parameters. scheme=null, host=null, path=
网上查找各种资料,大多数都是说 Target host must not be null, 这个错误要么是URL开头没有加http:// 要么就URL是有非法字符的说法,但是我这边检查了很多次, URL完全符合访问要求,pc浏览器试过,然后手机自带的浏览器也可以访问,所以问题重点就出现在 or set in parameters。scheme = null,host = null,path = / guard /; jsessionid = AE0C1D08BE0EC9824E18510FA6FDF969 简单明了就是没有配置sessionid 也就是 cookieStore
BUG出现环境:
由于业务需求,app有一个对设备升级的功能,需要连续访问后台返回给的2个URL,一个是登录的URL,一个是下载的URL,按照写后台的程序猿所说,我先是访问登录的URL ,然后返回成功后再访问下载的URL,可是不管用什么方法,都访问不了下载的URL,会报如标题的错误,
为了测试下载工具类的下载方法是否奏效,我访问了网络上其他的下载URL,结果发现是可以下载的,这说明我的下载方法没有问题,那么网络上其他的下载URL和我的下载URL的区别就出来了,问题也就知道在哪了,我们需要访问登录的URL后才能访问下载URL! 但是登录后,再次访问下载的URL地址时需要设置sessionid,也就是cookieStore才能正常下载,
楼主的解决方法:
这里用到了xutils.jar包里面的下载工具 点击这里下载xUtils-2.6.14.jar
在下载()方法执行之前需要设置cookieStore,才能访问登陆过的下载URL访问登录的时候,就需要拿到cookie
/* 验证 *//*** * @Description:获取网络数据* @param jsonElement* 参数* @param url 访问地址* @param @return* @return String*/public static String httpPostJson(JsonElement jsonElement, String url) {String result = "";try {// 创建连/* 建立HTTP Post联机 */HttpClient httpClient = new DefaultHttpClient();HttpPost post = new HttpPost(url);post.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);post.setEntity(new StringEntity(jsonElement.toString(), HTTP.UTF_8));// 发送HttpPost请求,并返回HttpResponse对象HttpResponse httpResponse = httpClient.execute(post);// 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求if (httpResponse.getStatusLine().getStatusCode() == 200) {// 获取返回结果result = EntityUtils.toString(httpResponse.getEntity());// 获取cookie MyCookieStore.cookieStore = ((DefaultHttpClient) httpClient).getCookieStore();}} catch (Exception e) {e.printStackTrace();return null;}return result;}
拿到cookieStore后存到MyCookieStore类里面,然后直接拿出来用
import com.lidroid.xutils.http.HttpHandler;private HttpHandler<File> mDownLoadHelper;mDownLoadHelper = new HttpUtils().configCookieStore(MyCookieStore.cookieStore).download(apkUrl, cachePath, true, false, new RequestCallBack<File>()
关键代码:配置这个就不会报错了,
configCookieStore(MyCookieStore.cookieStore)
附上:MyCookieStore类,
package com.bluetoothunlocknew.ui.licenseKey.lockVersionUpgrade;import org.apache.http.client.CookieStore;/*** 登录后缓存的cookie, 用于网络请求下载文件* Created by Administrator on 2018/8/29.*/
public class MyCookieStore {public static CookieStore cookieStore=null;}
附上源码:
//下载升级包操作,下载完成后会发送广播Intent mIntent = new Intent();Bundle bundle = new Bundle();bundle.putString("apkUrl", downloadUrl);mIntent.setClass(this, DownloadApkService.class);mIntent.putExtras(bundle);startService(mIntent);
// 注册接收服务registerReceiver(new String[] { ConstantsUtil.UPDATE_RECEIVED_ACTION });
/*** 接收广播*/@Overrideprotected void handleReceiver(Context context, Intent intent) {//常量类 public static final String UPDATE_RECEIVED_ACTION = "UPDATE_RECEIVED_ACTION";if (intent.getAction().equals(ConstantsUtil.UPDATE_RECEIVED_ACTION)) {//succee do something}//常量类 public static final String UPDATE_ERROR = "UPDATE_ERROR";if (intent.getAction().equals(ConstantsUtil.UPDATE_ERROR)) { //error}}
import java.io.File;
import java.text.DecimalFormat;import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;import com.bluetoothunlocknew.R;
import com.bluetoothunlocknew.app.InitApplication;
import com.bluetoothunlocknew.utils.ConstantsUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;/*** * @ClassName: DownloadApkService* @Description: 下载最新Apk文件服务工具类,通知栏显示进度,下载完成震动提示,**/
public class DownloadApkService extends Service {private final int NotificationID = 0x10000;private NotificationManager mNotificationManager = null;private Notification.Builder builder;private HttpHandler<File> mDownLoadHelper;/*** Title: onBind* @Description:* @param intent* @return* @see Service#onBind(Intent)*/@Overridepublic IBinder onBind(Intent intent) {return null;}/*** Title: onCreate* @Description:* @see Service#onCreate()*/@Overridepublic void onCreate() {super.onCreate();}/*** Title: onStartCommand* @Description:* @param intent* @param flags* @param startId* @return* @see Service#onStartCommand(Intent, int, int)*/@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("onStartCommand");// 接收Intent传来的参数:Bundle bundle = intent.getExtras();String apkUrl = bundle.getString("apkUrl");
// String versionName = bundle.getString("versionName");downloadApk(apkUrl/*, versionName*/);// return super.onStartCommand(intent, flags, startId);return START_REDELIVER_INTENT;}// 下载配置文件private void downloadApk(final String apkUrl/*, String versionName*/) {// 创建保存路径File filePath = new File(InitApplication.SdCardFilePath + "/BlueToothUnlockNew/DownloadFile/", apkUrl.substring(apkUrl.lastIndexOf("/") + 1, apkUrl.length()));final String cachePath = filePath.getAbsolutePath();// 第一个参数fileUrl:文件url。// 第二个参数filePath:SD卡目标文件。// 第三个参数true: 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。// 第四个参数false: 如果从请求返回信息中获取到文件名,下载完成后自动重命名。mDownLoadHelper = new HttpUtils().configCookieStore(MyCookieStore.cookieStore).download(apkUrl, cachePath, true, false, new RequestCallBack<File>() {@Overridepublic void onStart() {super.onStart();System.out.println("开始下载文件");System.out.println(apkUrl);System.out.println(cachePath);mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);builder = new Notification.Builder(getApplicationContext());builder.setSmallIcon(R.drawable.app_logo);builder.setTicker("正在下载无线管理");builder.setContentText("正在下载,请稍后...");builder.setNumber(0);builder.setAutoCancel(true);mNotificationManager.notify(NotificationID, builder.build());}@Overridepublic void onLoading(long total, long current, boolean isUploading) {super.onLoading(total, current, isUploading);System.out.println("文件下载中");int x = Long.valueOf(current).intValue();int totalS = Long.valueOf(total).intValue();builder.setProgress(totalS, x, false);builder.setContentInfo(getPercent(x, totalS));mNotificationManager.notify(NotificationID, builder.build());}@Overridepublic void onSuccess(ResponseInfo<File> responseInfo) {System.out.println("文件下载完成");mNotificationManager.notify(NotificationID, builder.build());// 震动提示Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);vibrator.vibrate(1000L);// 参数是震动时间(long类型)stopSelf();mNotificationManager.cancel(NotificationID);// 发送广播至主界面安装apkIntent intent = new Intent(ConstantsUtil.UPDATE_RECEIVED_ACTION);intent.putExtra("filePath", cachePath);sendBroadcast(intent);}@Overridepublic void onFailure(HttpException error, String msg) {System.out.println("文件下载失败");System.out.println(error);System.out.println(msg);// 发送广播至主界面安装apkIntent intent = new Intent(ConstantsUtil.UPDATE_ERROR);intent.putExtra("error", "文件下载失败");sendBroadcast(intent);mNotificationManager.cancel(NotificationID);}@Overridepublic void onCancelled() {super.onCancelled();System.out.println("文件下载结束,停止下载器");mDownLoadHelper.cancel();}});}/*** * @param x* 当前值* @param total* 总值* @return 当前百分比* @Description:返回百分之值*/private String getPercent(int x, int total) {String result = "";// 接受百分比的值double x_double = x * 1.0;double tempresult = x_double / total;// 百分比格式,后面不足2位的用0补齐 ##.00%DecimalFormat df1 = new DecimalFormat("0.00%");result = df1.format(tempresult);return result;}/*** Title: onDestroy* @Description:* @see Service#onDestroy()*/@Overridepublic void onDestroy() {super.onDestroy();MyCookieStore.cookieStore = null; //清除cookie缓存stopSelf();}}