com.loopj.android.http.AsyncHttpClient Java Examples

The following examples show how to use com.loopj.android.http.AsyncHttpClient. 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: RecyclerFragment.java    From ListItemFold with MIT License 6 votes vote down vote up
private void loadData() {
    AsyncHttpClient client = new AsyncHttpClient();

    client.get(getActivity(), "https://moment.douban.com/api/stream/date/2015-06-09", new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            if (response != null) {
                final JSONArray posts = response.optJSONArray("posts");
                int length = posts.length();
                List<SimpleData> resultDatas = new ArrayList<SimpleData>(length);
                for (int i = 0; i < length; i++) {
                    JSONObject obj = posts.optJSONObject(i);
                    SimpleData data = new SimpleData();
                    data.content = obj.optString("abstract");
                    data.title = obj.optString("title");
                    data.url = obj.optString("url");
                    JSONArray thumbs = obj.optJSONArray("thumbs");
                    if (thumbs.length() > 0) {
                        JSONObject thumb = thumbs.optJSONObject(0);
                        thumb = thumb.optJSONObject("large");
                        if (thumb != null) {
                            data.picUrl = thumb.optString("url");
                            resultDatas.add(data);
                        }
                    }
                }
                mAdapter.addAll(resultDatas);
            }
        }
    });
}
 
Example #2
Source File: WriteAnswerActivity.java    From WeCenterMobile-Android with GNU General Public License v2.0 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.write_answer);
	actionBar = getActionBar();
	actionBar.setIcon(null);
	actionBar.setTitle("�ش�");
	actionBar.setDisplayUseLogoEnabled(false);
	actionBar.setDisplayHomeAsUpEnabled(true);
	actionBar.show();
	Intent intent = getIntent();
	question_id = intent.getStringExtra("questionid");
	attach_access_key = md5(getAttachKey());
	dp = getResources().getDimension(R.dimen.dp);
	editText = (EditText) findViewById(R.id.answerdetil);
	selectimg_horizontalScrollView = (HorizontalScrollView) findViewById(R.id.selectimg_horizontalScrollView);
	gridview = (GridView) findViewById(R.id.noScrollgridview);
	gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
	client = new AsyncHttpClient();
	myCookieStore = new PersistentCookieStore(this);
	client.setCookieStore(myCookieStore);
	progressDialog = new MyProgressDialog(this, "���ڼ�����", "���Ժ�...", false);
	gridviewInit();
}
 
Example #3
Source File: AsyncFileUpLoad.java    From WeCenterMobile-Android with GNU General Public License v2.0 6 votes vote down vote up
public AsyncFileUpLoad(Context context, String url, String filePath,
		CallBack callBack) {
	Log.i("url", url);
	Log.i("filePath", filePath);
	this.context = context;
	this.url = url;
	file = new File(filePath);
	NetworkState networkState = new NetworkState();
	client = new AsyncHttpClient();
	PersistentCookieStore mCookieStore = new PersistentCookieStore(context);
	client.setCookieStore(mCookieStore);
	if (networkState.isNetworkConnected(context)) {
		//Login();
		upLoad(callBack);
	} else {
		showTips(R.drawable.tips_error, R.string.net_break);
	}

}
 
Example #4
Source File: AskingFragmentActivity.java    From WeCenterMobile-Android with GNU General Public License v2.0 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle arg0) {
	// TODO Auto-generated method stub
	super.onCreate(arg0);
	setContentView(R.layout.question_pager);
	actionBar = getActionBar();
	actionBar.setIcon(null);
	actionBar.setTitle("提问");
	actionBar.setDisplayUseLogoEnabled(false);
	actionBar.setDisplayHomeAsUpEnabled(true);
	actionBar.show();
	text1 = new AskingFragment();
	text2 = new DetailFragment();
	text3 = new TagFragment();
	cursor = (ImageView) findViewById(R.id.cursor);
	attach_access_key = md5(getAttachKey());
	client = new AsyncHttpClient();
	myCookieStore = new PersistentCookieStore(this);
	client.setCookieStore(myCookieStore);
	progressDialog = new MyProgressDialog(this, "正在上传", "稍等...", false);
	InitTextView();
	InitImageView();
	InitViewPager();

}
 
Example #5
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP GET request with cookie which generate by own context
 *
 * @param context
 * @param url
 * @param responseHandler
 */
public static void getWithCookie(Context context, String url, AsyncHttpResponseHandler responseHandler) {
    AsyncHttpClient client = new AsyncHttpClient();
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    //  myCookieStore.clear();
    client.setCookieStore(myCookieStore);
    client.get(getAbsoluteUrl(url), responseHandler);

}
 
Example #6
Source File: MyAsyncHttpClient.java    From school_shop with MIT License 6 votes vote down vote up
public static AsyncHttpClient createClient(Context context) {
    AsyncHttpClient client = new AsyncHttpClient();
    PersistentCookieStore cookieStore = new PersistentCookieStore(context);
    client.setCookieStore(cookieStore);

    return client;
}
 
Example #7
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP GET request with cookies which are defined in hashmap
 *
 * @param context
 * @param url
 * @param hashMap
 * @param responseHandler
 */
public static void getUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) {
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    if (BasicUtils.judgeNotNull(hashMap)) {
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            Cookie cookie = new BasicClientCookie(key.toString(), value.toString());
            myCookieStore.addCookie(cookie);
        }
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.setCookieStore(myCookieStore);
    client.get(getAbsoluteUrl(url), responseHandler);
}
 
Example #8
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP POST request with cookie which generate by own context
 *
 * @param context
 * @param url
 * @param responseHandler
 */
public static void postWithCookie(Context context, String url, AsyncHttpResponseHandler responseHandler) {
    AsyncHttpClient client = new AsyncHttpClient();
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    //  myCookieStore.clear();
    client.setCookieStore(myCookieStore);
    client.post(getAbsoluteUrl(url), responseHandler);
}
 
Example #9
Source File: Helper.java    From KUAS-AP-Material with MIT License 6 votes vote down vote up
private static AsyncHttpClient init() {
	AsyncHttpClient client = new AsyncHttpClient();
	client.addHeader("Connection", "Keep-Alive");
	client.setTimeout(7 * 1000);
	client.setEnableRedirects(true, true, true);
	return client;
}
 
Example #10
Source File: Helper.java    From KUAS-AP-Material with MIT License 6 votes vote down vote up
private static AsyncHttpClient init() {
	AsyncHttpClient client = new AsyncHttpClient();
	client.addHeader("Connection", "Keep-Alive");
	client.setTimeout(10 * 1000);
	client.setEnableRedirects(true, true, true);
	return client;
}
 
Example #11
Source File: ApiHttpClient.java    From Cotable with Apache License 2.0 6 votes vote down vote up
/**
 * Set the httpclient with heads
 *
 * @param c client
 */
public static void setHttpClient(AsyncHttpClient c) {
    client = c;
    client.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    client.addHeader("Accept-Language", Locale.getDefault().toString());
    client.addHeader("Accept-Encoding", "gzip, deflate, sdch");
    client.addHeader("Host", HOST);
    client.addHeader("Connection", "keep-alive");
    client.setUserAgent(ApiClientHelper.getUserAgent());
}
 
Example #12
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP POST request with cookies which are defined in hashmap
 *
 * @param context
 * @param url
 * @param hashMap
 * @param responseHandler
 */
public static void postUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) {
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    if (BasicUtils.judgeNotNull(hashMap)) {
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            Cookie cookie = new BasicClientCookie(key.toString(), value.toString());
            myCookieStore.addCookie(cookie);
        }
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.setCookieStore(myCookieStore);
    client.post(getAbsoluteUrl(url), responseHandler);
}
 
Example #13
Source File: ListFragment.java    From ListItemFold with MIT License 6 votes vote down vote up
private void loadData() {
    AsyncHttpClient client = new AsyncHttpClient();

    client.get(getActivity(), "https://moment.douban.com/api/stream/date/2015-06-09", new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            if (response != null) {
                final JSONArray posts = response.optJSONArray("posts");
                int length = posts.length();
                List<SimpleData> resultDatas = new ArrayList<SimpleData>(length);
                for (int i = 0; i < length; i++) {
                    JSONObject obj = posts.optJSONObject(i);
                    SimpleData data = new SimpleData();
                    data.content = obj.optString("abstract");
                    data.title = obj.optString("title");
                    data.url = obj.optString("url");
                    JSONArray thumbs = obj.optJSONArray("thumbs");
                    if (thumbs.length() > 0) {
                        JSONObject thumb = thumbs.optJSONObject(0);
                        thumb = thumb.optJSONObject("large");
                        if (thumb != null) {
                            data.picUrl = thumb.optString("url");
                            resultDatas.add(data);
                        }
                    }
                }
                mAdapter.addAll(resultDatas);
            }
        }
    });
}
 
Example #14
Source File: AsyncHttpUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 上传文件
 *
 * @return
 */
public static void upLoadFile(String url, File file, AsyncHttpResponseHandler handler) throws FileNotFoundException {
    RequestParams params = new RequestParams();
    params.put("username", "张鸿洋");
    params.put("password", "123");
    params.put("mFile", file);
    AsyncHttpClient client = getHttpClient();
    client.addHeader("Content-disposition", "mFile=\"" + file.getName() + "\"");
    client.addHeader("APP-Key", "APP-Secret222");
    client.addHeader("APP-Secret", "APP-Secret111");
    client.post(url, params, handler);
}
 
Example #15
Source File: FlowAsyncClient.java    From flow-android with MIT License 6 votes vote down vote up
public static void get(HashMap<String, String> headers, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    final AsyncHttpClient specialClient = new AsyncHttpClient();

    for (String key : headers.keySet()) {
        specialClient.addHeader(key, headers.get(key));
    }
    specialClient.get(getAbsoluteUrl(url), params, responseHandler);
}
 
Example #16
Source File: SubscriptionManager.java    From pusher-websocket-android with MIT License 6 votes vote down vote up
public void sendSubscription(Subscription subscription) {
    String interest =  subscription.getInterest();
    InterestSubscriptionChange change = subscription.getChange();

    JSONObject json = new JSONObject();
    try {
        json.put("app_key", appKey);
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    }
    StringEntity entity = new StringEntity(json.toString(), "UTF-8");

    String url = options.buildNotificationURL("/clients/" + clientId + "/interests/" + interest);
    ResponseHandlerInterface handler = factory.newSubscriptionChangeHandler(subscription);
    AsyncHttpClient client = factory.newHttpClient();
    switch (change) {
        case SUBSCRIBE:
            client.post(context, url, entity, "application/json", handler);
            break;
        case UNSUBSCRIBE:
            client.delete(context, url, entity, "application/json", handler);
            break;
    }
}
 
Example #17
Source File: TokenRegistry.java    From pusher-websocket-android with MIT License 6 votes vote down vote up
private void update(String token, String cachedId) throws JSONException {
    String url = options.buildNotificationURL("/clients/" + cachedId + "/token");
    AsyncHttpClient client = factory.newHttpClient();
    StringEntity params = createRegistrationJSON(token);

    AsyncHttpResponseHandler handler = factory.newTokenUpdateHandler(
            cachedId, params, context, listenerStack, this
    );
    client.put(context, url, params, "application/json", handler);
}
 
Example #18
Source File: ImageLoadActivity.java    From android-opensource-library-56 with Apache License 2.0 6 votes vote down vote up
private void startLoad() {
    AsyncHttpClient client = new AsyncHttpClient();

    client.get(
            "http://farm3.staticflickr.com/2004/2249945112_caa85476ef_o.jpg",
            new BinaryHttpResponseHandler() {
                @Override
                public void onSuccess(byte[] binaryData) {
                    Log.d(TAG, "onSuccess");
                    Bitmap bitmap = BitmapFactory.decodeByteArray(
                            binaryData, 0, binaryData.length);
                    ImageView imageView = ((ImageView) findViewById(R.id.image));
                    imageView.setImageBitmap(bitmap);
                    imageView.setVisibility(View.VISIBLE);
                    findViewById(R.id.progress).setVisibility(View.GONE);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    error.printStackTrace();
                    Log.d(TAG, "onFailure");
                }
            });

    RequestParams param = new RequestParams();
    param.put("hpge", "fuga");

}
 
Example #19
Source File: MagPiClient.java    From magpi-android with MIT License 6 votes vote down vote up
protected void setAuth(Context context, AsyncHttpClient client, String verb, String url, String contentToEncode) {
    String currentDate = new SimpleDateFormat(DATE_FORMAT).format(new Date());

    String contentMd5 = SecurityUtils.md5(contentToEncode);
    String toSign = verb + "\n" + contentMd5 + "\n" + currentDate + "\n" + url;

    String hmac = SecurityUtils.Hmac(Config.APP_SECRET, toSign);
    client.addHeader("Datetime", currentDate);
    client.addHeader("Content-Md5", contentMd5);
    client.addHeader("Hmac", SecurityUtils.md5(Config.USER) + ":" + hmac);
    Log.e("HMAC", SecurityUtils.md5(Config.USER) + ":" + hmac);
}
 
Example #20
Source File: ProfileActivity.java    From endpoints-samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    UserProfile profile = getIntent().getParcelableExtra(Lock.AUTHENTICATION_ACTION_PROFILE_PARAMETER);
    Token token = getIntent().getParcelableExtra(Lock.AUTHENTICATION_ACTION_TOKEN_PARAMETER);
    TextView greetingTextView = (TextView) findViewById(R.id.welcome_message);
    greetingTextView.setText("Welcome " + profile.getName());
    ImageView profileImageView = (ImageView) findViewById(R.id.profile_image);
    if (profile.getPictureURL() != null) {
        ImageLoader.getInstance().displayImage(profile.getPictureURL(), profileImageView);
    }

    client = new AsyncHttpClient();
    client.addHeader("Authorization", "Bearer " + token.getIdToken());
    Button callAPIButton = (Button) findViewById(R.id.call_api_button);
    callAPIButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            callAPI();
        }
    });
}
 
Example #21
Source File: TextHttpResponseLoopHandler.java    From monolog-android with MIT License 6 votes vote down vote up
/**
 * Attempts to encode response bytes as string of set encoding
 *
 * @param charset     charset to create string with
 * @param stringBytes response bytes
 * @return String of set encoding or null
 */
public String getResponseString(byte[] stringBytes, String charset) {
    try {
        String toReturn = (stringBytes == null) ? null : new String(stringBytes, charset);
        if (toReturn != null && toReturn.startsWith(UTF8_BOM)) {
            return toReturn.substring(1);
        }
        return toReturn;
    } catch (UnsupportedEncodingException e) {
        AsyncHttpClient.log.e(LOG_TAG, "Encoding response into string failed", e);
        return null;
    }
}
 
Example #22
Source File: WelcomeActivity.java    From iMoney with Apache License 2.0 6 votes vote down vote up
/**
 * 更新APP
 */
private void updateApp() {
    startTime = System.currentTimeMillis(); // 获取系统当前的时间
    // 判断手机是否可以联网
    if (!NetStateUtil.isConnected(this)) {
        ToastUtil.show(WelcomeActivity.this, "网络异常!");
        toLoginPager();
    } else {
        String updateUrl = ApiRequestUrl.UPDATE; // 获取联网请求更新应用的路径
        // 使用AsyncHttpClient实现联网获取版本信息
        AsyncHttpClient client = new AsyncHttpClient();
        client.post(updateUrl, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String json) {
                LogUtils.json(TAG, json);
                // 使用fastJson解析json数据
                updateInfo = JSON.parseObject(json, UpdateInfo.class);
                handler.sendEmptyMessage(WHAT_DOWNLOAD_VERSION_SUCCESS);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                LogUtils.e(TAG, "Throwable:" + error.getMessage() + ",content:" + content);
                ToastUtil.show(WelcomeActivity.this, "联网获取更新数据失败!");
                toLoginPager();
            }
        });
    }
}
 
Example #23
Source File: MainActivity.java    From KLog with Apache License 2.0 4 votes vote down vote up
private void initData() {
    httpClient = new AsyncHttpClient();
    JSON_LONG = getResources().getString(R.string.json_long);
    JSON = getResources().getString(R.string.json);
    STRING_LONG = getString(R.string.string_long);
}
 
Example #24
Source File: ApiConnector.java    From AnimeTaste with MIT License 4 votes vote down vote up
private void get(String request, JsonHttpResponseHandler handler) {
	AsyncHttpClient client = new AsyncHttpClient();
       client.setTimeout(10000);
	client.get(request, null, handler);
}
 
Example #25
Source File: MainActivity.java    From Android-ImageManager with MIT License 4 votes vote down vote up
public MainActivity() {
    httpClient = new AsyncHttpClient();
    httpClient.getHttpClient().getParams().setParameter("http.protocol.single-cookie-header", true);
    httpClient.getHttpClient().getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
}
 
Example #26
Source File: V2EX.java    From v2ex-daily-android with Apache License 2.0 4 votes vote down vote up
public static void showUser(Context context, String username, JsonHttpResponseHandler responseHandler){
    DebugUtils.log("showUser");
    new AsyncHttpClient().get(context, API_URL + API_USER + "?username=" + username, responseHandler);
}
 
Example #27
Source File: V2EX.java    From v2ex-daily-android with Apache License 2.0 4 votes vote down vote up
public static void getReplies(Context context, int topicId, JsonHttpResponseHandler responseHandler){
    DebugUtils.log("getReplies");
    new AsyncHttpClient().get(context, API_URL + API_REPLIES + "?topic_id=" + topicId, responseHandler);
}
 
Example #28
Source File: V2EX.java    From v2ex-daily-android with Apache License 2.0 4 votes vote down vote up
public static void showTopicByTopicId(Context context, int topicId, JsonHttpResponseHandler responseHandler){
    DebugUtils.log("showTopicByTopicId");
    new AsyncHttpClient().get(context, API_URL + API_TOPIC + "?id=" + topicId, responseHandler);
}
 
Example #29
Source File: HttpUtil.java    From Libraries-for-Android-Developers with MIT License 4 votes vote down vote up
public static AsyncHttpClient getClient()
{
    return client;
}
 
Example #30
Source File: EssayCommentActivity.java    From WeCenterMobile-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.comment_list);

	ActionBar actionBar = getActionBar();
	actionBar.setIcon(null);
	actionBar.setTitle("��������");
	actionBar.setDisplayUseLogoEnabled(false);
	actionBar.setDisplayHomeAsUpEnabled(true);
	actionBar.show();
	Intent intent = getIntent();
	id = intent.getStringExtra("artid");
	client = new AsyncHttpClient();
	myCookieStore = new PersistentCookieStore(this);
	client.setCookieStore(myCookieStore);
	comment = (EditText) findViewById(R.id.comment);
	publish = (ImageButton) findViewById(R.id.publish);
	publish.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			RequestParams params = new RequestParams();
			params.put("article_id", id);
			params.put("message", comment.getText().toString());
			params.put("at_uid", atuid);
			postcom(params);
			comment.setText("");
			refresh();
		}
	});
	comitems = new ArrayList<EssayCommentModel>();
	imageDownLoader = new ImageDownLoader(this);
	comlist = (ListView) findViewById(R.id.comlist);
	isFirstEnter = true;
	comlist.setOnItemClickListener(this);
	comlist.setOnScrollListener(this);

	Getcom(id);

}