com.lidroid.xutils.exception.HttpException Java Examples

The following examples show how to use com.lidroid.xutils.exception.HttpException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SyncHttpHandler.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        ResponseStream responseStream = new ResponseStream(response, charset, requestUrl, expiry);
        responseStream.setRequestMethod(requestMethod);
        return responseStream;
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
 
Example #2
Source File: HttpFragment.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
/**
	 * post请求数据
	 * @param view
	 */
	@OnClick(R.id.post)
	public void post(View view) {
		//这个地址只支持get, 这里只是示范。
		String url = "http://www.weather.com.cn/data/cityinfo/101010100.html"; 
		RequestParams params = new RequestParams();
		/*		//添加请求参数
		params.addBodyParameter(key, value);*/
		
/*		//添加请求头
		params.addHeader(name, value);*/
		http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				data.setText(responseInfo.result);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(getActivity(), "访问失败" + msg, Toast.LENGTH_SHORT).show();
			}
			
		});
		
	}
 
Example #3
Source File: HttpFragment.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
/**
	 * get请求数据
	 * @param view
	 */
	@OnClick(R.id.get)
	public void get(View view) {
		String url = "http://www.weather.com.cn/data/cityinfo/101010100.html";
		RequestParams params = new RequestParams();
/*		//添加请求参数
		params.addBodyParameter(key, value);*/
		
/*		//添加请求头
		params.addHeader(name, value);*/
		http.send(HttpMethod.GET, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				data.setText(responseInfo.result);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(getActivity(), "访问失败" + msg, Toast.LENGTH_SHORT).show();
			}
			
		});
	}
 
Example #4
Source File: QuTuServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
	public void refush(final Handler handler, int newOrHotFlag, int count) {
		HttpUtils http = new HttpUtils();
		http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
		http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
//		params.addQueryStringParameter("offset", String.valueOf(1));
		params.addQueryStringParameter("count", String.valueOf(count));
		http.send(HttpRequest.HttpMethod.GET,
			RcpUri.INTERFACE_URI_LIST, params,
			new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						handler.sendEmptyMessage(Constants.FAILURE);
						return;
					}
					PageResult page = FastjsonUtil.deserialize(
							map.get("data").toString(), PageResult.class);
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putSerializable("pageResult", page);
					message.what = Constants.SUCCESS_1;
					message.setData(bundle);
					handler.sendMessage(message);
				}
				@Override
				public void onFailure(HttpException error, String msg) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			});
	}
 
Example #5
Source File: DownloadManager.java    From AndroidAppCodeFramework with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(HttpException error, String msg) {
    HttpHandler<File> handler = downloadInfo.getHandler();
    if (handler != null) {
        downloadInfo.setState(handler.getState());
    }
    try {
        db.saveOrUpdate(downloadInfo);
    } catch (DbException e) {
        LogUtils.e(e.getMessage(), e);
    }
    if (baseCallBack != null) {
        baseCallBack.onFailure(error, msg);
    }
}
 
Example #6
Source File: DownloadManager.java    From AndroidAppCodeFramework with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(HttpException error, String msg) {
    HttpHandler<File> handler = downloadInfo.getHandler();
    if (handler != null) {
        downloadInfo.setState(handler.getState());
    }
    try {
        db.saveOrUpdate(downloadInfo);
    } catch (DbException e) {
        LogUtils.e(e.getMessage(), e);
    }
    if (baseCallBack != null) {
        baseCallBack.onFailure(error, msg);
    }
}
 
Example #7
Source File: JokeServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void getJokeById(final ApiCallBack apiCallBack, Integer jokeId) {
	HttpUtils http = new HttpUtils();
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	http.configDefaultHttpCacheExpiry(0); 
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_GET_JOKE, params,
		new RequestCallBack<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if(code == Constants.SUCCESS) {
					Log.e(TAG, "getJokeById success");
					Joke joke = FastjsonUtil.deserialize(
							map.get("data").toString(), Joke.class);
					apiCallBack.onSuccess(joke);
				} else {
					Log.e(TAG, "getJokeById fail, fail msg is " + map.get("msg"));
					apiCallBack.onFailure(String.valueOf(code));
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "getJokeById error", error);
				if(!HttpUtil.isNetworkAvailable(mContext)) {
					ToastUtils.showMessage(mContext, R.string.no_net);
				} else {
					apiCallBack.onError(error, msg);
				}
			}
		});
}
 
Example #8
Source File: PullService.java    From ALLGO with Apache License 2.0 5 votes vote down vote up
private void getOnePull() {
	SharedPreferences sharedPref = this.getSharedPreferences("userdata",Context.MODE_PRIVATE);
	RequestParams params = new RequestParams();
       params.addQueryStringParameter("uid", sharedPref.getInt("uid", -1) + "");
       SharedPreferences sharedPref1 = this.getSharedPreferences("appdata",Context.MODE_PRIVATE);
	params.addHeader("Cookie","JSESSIONID="+sharedPref1.getString("SessionId", ""));
       
       HttpUtils http = new HttpUtils();
       http.send(HttpRequest.HttpMethod.GET,
       		declare.getHost_url() + "remind/unread",
               params,
               new RequestCallBack<String>() {

				@Override
                   public void onStart() {
                   	Log.i(TAG ,"Pull==>onStart" ) ;
                   }

                   @Override
                   public void onLoading(long total, long current, boolean isUploading) {
                   }

                   @Override
                   public void onSuccess(ResponseInfo<String> responseInfo) {
					readingParse(responseInfo.result);
                   }
                   @Override
                   public void onFailure(HttpException error, String msg) {
                   	Log.i(TAG ,"Pull==>error==>" +  msg ) ;
                   }
               });
}
 
Example #9
Source File: test.java    From ALLGO with Apache License 2.0 5 votes vote down vote up
public void test5(){

        //RequestParams params = new RequestParams();
        //params.addHeader("name", "value");
        //params.addQueryStringParameter("name", "value");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                "http://www.baidu.com",
                //params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                    	Log.i("Http" ,"onStart" ) ;
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                    	Log.i("Http" , "onSuccess" + responseInfo.result ) ;
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                    	Log.i("Http" ,"error==>" +  msg ) ;
                    }
                });
    }
 
Example #10
Source File: JokeServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void getCommentByJokeId(final Handler handler, int jokeId, int offset,
		int count) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(60); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("qushiId", String.valueOf(jokeId));
	params.addQueryStringParameter("offset", String.valueOf(offset));
	params.addQueryStringParameter("count", String.valueOf(count));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_GET_COMMENTS, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					handler.sendEmptyMessage(Constants.FAILURE);
					return;
				}
				PageResult page = FastjsonUtil.deserialize(
						map.get("data").toString(), PageResult.class);
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable("pageResult", page);
				message.what = Constants.SUCCESS;
				message.setData(bundle);
				handler.sendMessage(message);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #11
Source File: test.java    From ALLGO with Apache License 2.0 5 votes vote down vote up
public void test4(){
       RequestParams params = new RequestParams();
       params.addQueryStringParameter("uname", "中文");
       HttpUtils http = new HttpUtils();
       http.send(HttpRequest.HttpMethod.POST,
               "http://192.168.1.104:8080/ALLGO_SERVER/login",
               params,
               new RequestCallBack<String>() {

                   @Override
                   public void onStart() {
                   	Log.i("Http" ,"onStart" ) ;
                   }

                   @Override
                   public void onLoading(long total, long current, boolean isUploading) {
                   }

                   @Override
                   public void onSuccess(ResponseInfo<String> responseInfo) {
                   	Log.i("Http" , "onSuccess" + responseInfo.result ) ;
                   }

                   @Override
                   public void onFailure(HttpException error, String msg) {
                   	Log.i("Http" ,"error==>" +  msg ) ;
                   }
               });
}
 
Example #12
Source File: BitMapFragment.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
/**
 * @param url
 */
private void loadImgList(String url) {
       new HttpUtils().send(HttpRequest.HttpMethod.GET, url,
               new RequestCallBack<String>() {
                   @Override
                   public void onSuccess(ResponseInfo<String> responseInfo) {
                   	adapter.addSrc(getImgSrcList(responseInfo.result));
                   	adapter.notifyDataSetChanged();//通知listview更新数据
                   }

                   @Override
                   public void onFailure(HttpException error, String msg) {
                   }
               });
   }
 
Example #13
Source File: JokeServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void refushAll(final Handler handler, int newOrHotFlag, int count) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(0); //缓存超期时间0分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
	params.addQueryStringParameter("count", String.valueOf(count));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_LIST, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					String rs = responseInfo.result;
					Map map = FastjsonUtil.json2Map(rs);
					int code = Integer.parseInt(String.valueOf(map.get("code")));
					if (code != 200) {
						//请求失败
						handler.sendEmptyMessage(Constants.FAILURE);
						return;
					}
					PageResult page = FastjsonUtil.deserialize(
							map.get("data").toString(), PageResult.class);
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putSerializable("pageResult", page);
					message.what = Constants.SUCCESS_1;
					message.setData(bundle);
					handler.sendMessage(message);
				} catch (Exception e) {
					handler.sendEmptyMessage(Constants.FAILURE);
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #14
Source File: MeiTuServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void refresh(final Handler handler, int newOrHotFlag, int count) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(0); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
	params.addQueryStringParameter("count", String.valueOf(count));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_LIST, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					handler.sendEmptyMessage(Constants.FAILURE);
					return;
				}
				PageResult page = FastjsonUtil.deserialize(
						map.get("data").toString(), PageResult.class);
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable("pageResult", page);
				message.what = Constants.SUCCESS_1;
				message.setData(bundle);
				handler.sendMessage(message);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #15
Source File: MeiTuServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void getMeiTu(final Handler handler, int newOrHotFlag, int offset,
		int count) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
	params.addQueryStringParameter("offset", String.valueOf(offset));
	params.addQueryStringParameter("count", String.valueOf(count));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_LIST, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					handler.sendEmptyMessage(Constants.FAILURE);
					return;
				}
				PageResult page = FastjsonUtil.deserialize(
						map.get("data").toString(), PageResult.class);
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable("pageResult", page);
				message.what = Constants.SUCCESS;
				message.setData(bundle);
				handler.sendMessage(message);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #16
Source File: QuTuServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void getQuTu(final Handler handler, int newOrHotFlag, int offset,
		int count) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("newOrHotFlag", String.valueOf(newOrHotFlag));
	params.addQueryStringParameter("offset", String.valueOf(offset));
	params.addQueryStringParameter("count", String.valueOf(count));
	http.send(HttpRequest.HttpMethod.GET,
		RcpUri.INTERFACE_URI_LIST, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					handler.sendEmptyMessage(Constants.FAILURE);
					return;
				}
				PageResult page = FastjsonUtil.deserialize(
						map.get("data").toString(), PageResult.class);
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable("pageResult", page);
				message.what = Constants.SUCCESS;
				message.setData(bundle);
				handler.sendMessage(message);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #17
Source File: UserServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void reSetPassword(String phone, String password,
		final ApiCallBack apiCallBack) {
	HttpUtils http = new HttpUtils();
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	http.configDefaultHttpCacheExpiry(0); 
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("phone", phone);
	params.addQueryStringParameter("password", password);
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_RESET_PWD, params,
		new RequestCallBack<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if(code == Constants.SUCCESS) {
					Log.e(TAG, "reSetPassword success");
					User user = FastjsonUtil.deserialize(
							map.get("data").toString(), User.class);
					apiCallBack.onSuccess(user);
				} else {
					Log.e(TAG, "reSetPassword fail, fail msg is " + map.get("msg"));
					apiCallBack.onFailure(String.valueOf(code));
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "reSetPassword error", error);
				if(!HttpUtil.isNetworkAvailable(mContext)) {
					ToastUtils.showMessage(mContext, R.string.no_net);
				} else {
					apiCallBack.onError(error, msg);
				}
			}
		});
}
 
Example #18
Source File: UserServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void checkUserExeist(String phone, final ApiCallBack apiCallBack) {
	HttpUtils http = new HttpUtils();
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	http.configDefaultHttpCacheExpiry(0); 
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("phone", phone);
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_CHECK_EXEIST, params,
		new RequestCallBack<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if(code == Constants.SUCCESS) {
					Log.e(TAG, "checkUserExeist success");
					apiCallBack.onSuccess(code);
				} else {
					Log.e(TAG, "checkUserExeist fail, fail msg is " + map.get("msg"));
					apiCallBack.onFailure(String.valueOf(code));
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "checkUserExeist error", error);
				if(!HttpUtil.isNetworkAvailable(mContext)) {
					ToastUtils.showMessage(mContext, R.string.no_net);
				} else {
					apiCallBack.onError(error, msg);
				}
			}
		});
}
 
Example #19
Source File: DownFragment.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.start)
public void start(View view) {
	if (handler == null || handler.isCancelled()) {
		handler = http.download(URL, 
				Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.apk", 
				true,  // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
				false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
				new RequestCallBack<File>() {

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						super.onLoading(total, current, isUploading);
						progressBar.setMax((int) total);
						progressBar.setProgress((int) current);
					}

					@Override
					public void onSuccess(ResponseInfo<File> responseInfo) {
						Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_SHORT).show();
						progressBar.setProgress(0);
						start.setText("开始");
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						Toast.makeText(getActivity(), "下载失败" + msg, Toast.LENGTH_SHORT).show();
						start.setText("开始");
					}
				});
		start.setText("暂停");
	}
	else {
		handler.cancel();
		start.setText("开始");
	}
}
 
Example #20
Source File: UserServiceImpl.java    From QiQuYing with Apache License 2.0 5 votes vote down vote up
@Override
public void setPortrait(final Handler handler, String userId, String portraitURL) {
	Log.e(TAG, "setPortrait");
	HttpUtils http = new HttpUtils();
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("userId", userId);
	params.addQueryStringParameter("portraitURL", portraitURL);
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_SET_PORTRAIT, params,
		new RequestCallBack<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if(code == Constants.SUCCESS) {
					Log.e(TAG, "set portrait success");
					handler.sendEmptyMessage(Constants.SUCCESS_1);
				} else {
					Log.e(TAG, "set portrait fail, fail msg is " + map.get("msg"));
					handler.sendEmptyMessage(Constants.FAILURE_1);
					ToastUtils.showMessage(mContext,
							R.string.set_portrait_fail);
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "set portrait error", error);
				handler.sendEmptyMessage(Constants.FAILURE_1);
				if(!HttpUtil.isNetworkAvailable(mContext)) {
					ToastUtils.showMessage(mContext, R.string.no_net);
				} else {
					ToastUtils.showMessage(mContext,
							R.string.set_portrait_fail);
				}
			}
		});
}
 
Example #21
Source File: HttpHandler.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
@Override
protected Void doInBackground(Object... params) {
    if (this.state == State.CANCELLED || params == null || params.length == 0) return null;

    //主要是判断是否是下载文件
    if (params.length > 3) {
        fileSavePath = String.valueOf(params[1]);
        isDownloadingFile = fileSavePath != null;
        autoResume = (Boolean) params[2];
        autoRename = (Boolean) params[3];
    }

    try {
        if (this.state == State.CANCELLED) return null;
        // init request & requestUrl
        request = (HttpRequestBase) params[0];
        requestUrl = request.getURI().toString();
        if (callback != null) {
            callback.setRequestUrl(requestUrl);
        }

        this.publishProgress(UPDATE_START); //回调, 开始

        lastUpdateTime = SystemClock.uptimeMillis();

        ResponseInfo<T> responseInfo = sendRequest(request);
        if (responseInfo != null) {
            this.publishProgress(UPDATE_SUCCESS, responseInfo); //回调, 成功
            return null;
        }
    } catch (HttpException e) {
        this.publishProgress(UPDATE_FAILURE, e, e.getMessage()); //回调, 失败
    }

    return null;
}
 
Example #22
Source File: HttpHandler.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void onProgressUpdate(Object... values) {
    if (this.state == State.CANCELLED || values == null || values.length == 0 || callback == null) return;
    switch ((Integer) values[0]) {
        case UPDATE_START:
            this.state = State.STARTED;
            callback.onStart();
            break;
        case UPDATE_LOADING:
            if (values.length != 3) return;
            this.state = State.LOADING;
            callback.onLoading(
                    Long.valueOf(String.valueOf(values[1])),
                    Long.valueOf(String.valueOf(values[2])),
                    isUploading);
            break;
        case UPDATE_FAILURE:
            if (values.length != 3) return;
            this.state = State.FAILURE;
            callback.onFailure((HttpException) values[1], (String) values[2]);
            break;
        case UPDATE_SUCCESS:
            if (values.length != 2) return;
            this.state = State.SUCCESS;
            callback.onSuccess((ResponseInfo<T>) values[1]);
            break;
        default:
            break;
    }
}
 
Example #23
Source File: LoadEmojiUtils.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
private static void loadSmileyZip(final Context context, String url) {
//        ZogUtils.printError(LoadEmojiUtils.class, "loadSmileyZip  url:" + url);
        initDir(context);
        HttpUtils http = new HttpUtils();
        http.download(url, SmileyUtils.getSmileyZipFilePath(context),
                true,// 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将重新下载。
                false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        ZogUtils.printError(LoadEmojiUtils.class, "loadSmileyZip  onStart");

                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        ZogUtils.printError(LoadEmojiUtils.class, "loadSmileyZip onSuccess dir:" + responseInfo.result.getPath());

                        SmileyInfo smileyInfo = AppSPUtils.getContentConfig(context).getSmileyInfo();
                        String fileMD5 = MD5Utils.getFileMD5(new File(SmileyUtils.getSmileyZipFilePath(context)));

                        ZogUtils.printError(LoadEmojiUtils.class, "fileMD5:" + fileMD5 + " smileyInfo.getMD5()):" + smileyInfo.getMD5());

//                        if (fileMD5.equals(smileyInfo.getMD5())) {
                        loadSmileyMap(context);
//                        } else {
//                            ZogUtils.printError(LoadEmojiUtils.class, "Smiley Zip MD5不匹配");
//                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        ZogUtils.printError(LoadEmojiUtils.class, "loadSmileyZip onFailure");
                        SmileyUtils.distory(context);
//                        JsonUtils.printAsJson(e);
//                        ToastUtils.mkLongTimeToast(context, context.getString(R.string.download_emoji_fail));
                    }
                });
    }
 
Example #24
Source File: PayHelperUtils.java    From Hook with Apache License 2.0 5 votes vote down vote up
public static void getTradeInfo(final Context paramContext, final String paramString) {
        Log.i("tag", "getTradeInfo:1 ");
        long l = System.currentTimeMillis();
        String str1 = getCurrentDate();
        String str2 = "https://mbillexprod.alipay.com/enterprise/simpleTradeOrderQuery.json?beginTime=" + (l - 864000000L) + "&limitTime=" + l + "&pageSize=20&pageNum=1&channelType=ALL";
        HttpUtils localHttpUtils = new HttpUtils(15000);
        localHttpUtils.configResponseTextCharset("GBK");
        RequestParams localRequestParams = new RequestParams();
        localRequestParams.addHeader("Cookie", paramString);
        localRequestParams.addHeader("Referer", "https://render.alipay.com/p/z/merchant-mgnt/simple-order.html?beginTime=" + str1 + "&endTime=" + str1 + "&fromBill=true&channelType=ALL");
        localHttpUtils.send(HttpRequest.HttpMethod.GET, str2, localRequestParams, new RequestCallBack() {
            public void onFailure(HttpException paramAnonymousHttpException, String paramAnonymousString) {
//                PayHelperUtils.sendmsg(PayHelperUtils.this, "服务器异常" + paramAnonymousString);
                Log.i("tag", "服务器异常");
            }

            public void onSuccess(ResponseInfo paramAnonymousResponseInfo) {
                String result = (String) paramAnonymousResponseInfo.result;
                try {
                    Log.i("tag", "getTradeInfo2" + result);
                    JSONArray array = new JSONObject(result).getJSONObject("result").getJSONArray("list");
                    if ((array != null) && (array.length() > 0)) {
                        String json = array.getJSONObject(0).getString("tradeNo");
                        Log.i("tag", "getTradeInfo3" + json);
                        Intent localIntent = new Intent();
                        localIntent.putExtra("tradeno", json);
                        localIntent.putExtra("cookie", paramString);
                        localIntent.setAction(Constans.ACTION_PAY_SUCCESS);
                        paramContext.sendBroadcast(localIntent);
//                        EventBus.getDefault().post(new MessageEvent(MessageEvent.MessageType.TRADENORECEIVED_ACTION,json,paramString));
                    }
                    return;
                } catch (Exception p) {
//                    PayHelperUtils.sendmsg(PayHelperUtils.this, "getTradeInfo异常" + paramAnonymousResponseInfo.getMessage());
                    Log.i("tag", "getTradeInfo异常" + p.getMessage());
                }
            }
        });
    }
 
Example #25
Source File: JokeServiceImpl.java    From QiQuYing with Apache License 2.0 4 votes vote down vote up
@Override
public void ding(final List<DingOrCai> dingOrCais) {
	if(dingOrCais == null || dingOrCais.size() == 0) {
		return;
	}
	StringBuilder sb = new StringBuilder();
	for (DingOrCai dingOrCai : dingOrCais) {
		sb.append(dingOrCai.getJokeId()).append(",");
	}
	String ids = sb.toString().substring(0, sb.toString().length() - 1);
	HttpUtils http = new HttpUtils();
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("ids", ids);
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_DING, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					Log.e(TAG, "ding failure:" + map.get("desc"));
					return;
				}
				//修改本地数据库
				TaskExecutor.executeTask(new Runnable() {
					@Override
					public void run() {
						mDingCaiDAO.upload(dingOrCais);
					}
				});
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "ding failure", error);
			}
		});
}
 
Example #26
Source File: HttpUtils.java    From android-open-project-demo with Apache License 2.0 4 votes vote down vote up
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url) throws HttpException {
    return sendSync(method, url, null);
}
 
Example #27
Source File: HttpUtils.java    From android-open-project-demo with Apache License 2.0 4 votes vote down vote up
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url, RequestParams params) throws HttpException {
    if (url == null) throw new IllegalArgumentException("url may not be null");

    HttpRequest request = new HttpRequest(method, url);
    return sendSyncRequest(request, params);
}
 
Example #28
Source File: NetUtil.java    From ALLGO with Apache License 2.0 4 votes vote down vote up
private void send(HttpRequest.HttpMethod arg0,RequestParams params){
	SharedPreferences sharedPref = context.getSharedPreferences("appdata",Context.MODE_PRIVATE);
	params.addHeader("Cookie","JSESSIONID="+sharedPref.getString("SessionId", ""));
	http = new HttpUtils();
	http.configCurrentHttpCacheExpiry(1000 * 1);
    http.send(arg0,
    		declare.getHost_url() + uri,
    		params,
            new RequestCallBack<String>() {

				@Override
                public void onStart() {
                	Log.i(TAG ,"onStart" ) ;
                }
				
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                	Log.i(TAG, "Http==>"+responseInfo.result);
					try {
						jsonObject = new JSONObject(responseInfo.result);
						 if(jsonObject.getString("response").equals("error")){
							refresh.refresh(jsonObject.getJSONObject("error").getString("text"), -1);
						 }else if(jsonObject.getString("response").equals("notlogin")){
							 Toast.makeText(context, "登录过期,请重新登录", Toast.LENGTH_SHORT).show();
							 Intent intent = new Intent(context,LogOffACTIVITY.class);
							 intent.putExtra("action", 1);
							 context.startActivity(intent);
						 }else {
							 callback.getResult(jsonObject);
						 }
					} catch (JSONException e) {
						e.printStackTrace();
					}
                }
                @Override
                public void onFailure(HttpException error, String msg) {
                	Log.i(TAG ,"error==>" +  msg ) ;
                	refresh.refresh(msg, -1);
                }
            });
}
 
Example #29
Source File: UserServiceImpl.java    From QiQuYing with Apache License 2.0 4 votes vote down vote up
@Override
public void addTencentUser(final Handler handler, String openId, String portraitUrl, String nickName,
		int sex) {
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("openId", openId);
	params.addQueryStringParameter("portraitUrl", portraitUrl);
	try {
		params.addQueryStringParameter("nickName", URLEncoder.encode(nickName, "UTF-8"));
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	params.addQueryStringParameter("sex", String.valueOf(sex));
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_ADD_TENCENT_USER, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					handler.sendEmptyMessage(Constants.FAILURE);
					Log.e(TAG, "save user failure");
					return;
				}
				Log.e(TAG, "save user success");
				User user = FastjsonUtil.deserialize(
						map.get("data").toString(), User.class);
				Message message = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable("user", user);
				message.what = Constants.SUCCESS;
				message.setData(bundle);
				handler.sendMessage(message);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "save user failure", error);
				handler.sendEmptyMessage(Constants.FAILURE);
			}
		});
}
 
Example #30
Source File: JokeServiceImpl.java    From QiQuYing with Apache License 2.0 4 votes vote down vote up
@Override
public void addComment(final Handler handler, Integer jokeId, String content) {
	if(App.currentUser == null || Util.isEmpty(content)) {
		return;
	}
	HttpUtils http = new HttpUtils();
	http.configDefaultHttpCacheExpiry(1000 * 60 * 10); //缓存超期时间10分钟
	http.configTimeout(Constants.REQUEST_TIME_OUT);  //设置超时时间
	RequestParams params = new RequestParams();
	params.addQueryStringParameter("jokeId", String.valueOf(jokeId));
	params.addQueryStringParameter("userId", String.valueOf(App.currentUser.getId()));
	params.addQueryStringParameter("userPortrait", App.currentUser.getPortraitUrl());
	try {
		params.addQueryStringParameter("userNick", 
				URLEncoder.encode(App.currentUser.getUserNike(), "UTF-8"));
		params.addQueryStringParameter("content", 
				URLEncoder.encode(content, "UTF-8"));
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	http.send(HttpRequest.HttpMethod.POST,
		RcpUri.INTERFACE_URI_COMMENT, params,
		new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String rs = responseInfo.result;
				Map map = FastjsonUtil.json2Map(rs);
				int code = Integer.parseInt(String.valueOf(map.get("code")));
				if (code != 200) {
					//请求失败
					Log.e(TAG, "comment failure");
					ToastUtils.showMessage(mContext, R.string.comment_fail);
					handler.sendEmptyMessage(Constants.FAILURE_1);
					return;
				}
				Log.e(TAG, "comment success");
				handler.sendEmptyMessage(Constants.SUCCESS_1);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e(TAG, "comment failure", error);
				handler.sendEmptyMessage(Constants.FAILURE_1);
				if(!HttpUtil.isNetworkAvailable(mContext)) {
					ToastUtils.showMessage(mContext, R.string.no_net);
				} else {
					ToastUtils.showMessage(mContext, R.string.comment_fail);
				}
			}
		});
}