cz.msebera.android.httpclient.Header Java Examples

The following examples show how to use cz.msebera.android.httpclient.Header. 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: Helper.java    From KUAS-AP-Material with MIT License 6 votes vote down vote up
public static void getNews(final Context context) {
	mClient.get(NEWS_URL, new JsonHttpResponseHandler() {

		@Override
		public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
			super.onSuccess(statusCode, headers, response);
			try {
				Memory.setString(context, Constant.PREF_NEWS_TITLE, response.getString(2));
				Memory.setString(context, Constant.PREF_NEWS_CONTENT, response.getString(3));
				Memory.setString(context, Constant.PREF_NEWS_URL, response.getString(4));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	});
}
 
Example #2
Source File: HttpWebConnection.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an HttpMethod into a WebResponse.
 */
private WebResponse makeWebResponse(final HttpResponse httpResponse,
        final WebRequest request, final DownloadedContent responseBody, final long loadTime) {

    String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
    if (statusMessage == null) {
        statusMessage = "Unknown status message";
    }
    final int statusCode = httpResponse.getStatusLine().getStatusCode();
    final List<NameValuePair> headers = new ArrayList<>();
    for (final Header header : httpResponse.getAllHeaders()) {
        headers.add(new NameValuePair(header.getName(), header.getValue()));
    }
    final WebResponseData responseData = new WebResponseData(responseBody, statusCode, statusMessage, headers);
    return newWebResponseInstance(responseData, loadTime, request);
}
 
Example #3
Source File: IMSocketManager.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * todo check exception
 * */
public void sendRequest(GeneratedMessageLite requset,int sid,int cid,Packetlistener packetlistener){
    int seqNo = 0;
    try{
        //组装包头 header
        com.mogujie.tt.protobuf.base.Header header = new DefaultHeader(sid, cid);
        int bodySize = requset.getSerializedSize();
        header.setLength(SysConstant.PROTOCOL_HEADER_LENGTH + bodySize);
        seqNo = header.getSeqnum();
        listenerQueue.push(seqNo,packetlistener);
        boolean sendRes = msgServerThread.sendRequest(requset,header);
    }catch (Exception e){
        if(packetlistener !=null){
            packetlistener.onFaild();
        }
        listenerQueue.pop(seqNo);
        logger.e("#sendRequest#channel is close!");
    }
}
 
Example #4
Source File: ReplyReview.java    From StreamHub-Android-SDK with MIT License 6 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
    super.onFailure(statusCode, headers, throwable, errorResponse);
    dismissProgressDialog();
    Log.d("data error", "" + errorResponse);
    try {
        if (!errorResponse.isNull("msg")) {
            showAlert(errorResponse.getString("msg"), "TRY AGAIN", tryAgain);
        } else {
            showAlert("Something went wrong.", "TRY AGAIN", tryAgain);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        showAlert("Something went wrong.", "TRY AGAIN", tryAgain);
    }
}
 
Example #5
Source File: TokenUpdateHandler.java    From pusher-websocket-android with MIT License 6 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    String log = "[token update] Received status " + statusCode;
    String responseBodyString;

    if (responseBody != null) {
        responseBodyString = new String(responseBody);
        log += " with: " + responseBodyString;
    } else {
        responseBodyString = "[no body]";
    }
    Log.e(TAG, log);

    // the client ID cannot be found and we need to re-register to get a fresh one.
    // If the 404 is for a different reason, it'll fall down at the next hurdle
    // (uploading the token) anyway.
    if (statusCode == 404) {
        this.invalidClientIdHandler.onInvalidClientId(retryParams);
    } else {
        listenerStack.onFailedRegistration(statusCode, responseBodyString);
    }
}
 
Example #6
Source File: NewActivity.java    From StreamHub-Android-SDK with MIT License 6 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
    super.onFailure(statusCode, headers, throwable, errorResponse);
    dismissProgressDialog();
    try {
        if (!errorResponse.isNull("msg")) {
            showAlert(errorResponse.getString("msg"), "TRY AGAIN", tryAgain);
        } else {
            showAlert("Something went wrong.", "TRY AGAIN", tryAgain);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        showAlert("Something went wrong.", "TRY AGAIN", tryAgain);

    }
}
 
Example #7
Source File: ReviewInDetailAdapter.java    From StreamHub-Android-SDK with MIT License 6 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    super.onSuccess(statusCode, headers, response);
    Log.d("action ClientCall", "success" + response);
    if (!response.isNull("data")) {
        try {
            JSONObject data = response.getJSONObject("data");
            if (!data.isNull("messageId")) {
                if (data.getString("messageId").equals(mainReviewId)) {
                    if (dialog.isShowing())
                        dismissProgress();
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    if (dialog.isShowing())
        dismissProgress();
}
 
Example #8
Source File: ReviewInDetailAdapter.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
    super.onFailure(statusCode, headers, throwable, errorResponse);
    dismissProgress();
    Log.d("action ClientCall", throwable + "");
    showToast("Something went wrong.");
}
 
Example #9
Source File: ReviewsActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    super.onSuccess(statusCode, headers, response);
    swipeView.setRefreshing(false);
    application.printLog(false, TAG + "-InitCallback-onSuccess", response.toString());
    (new ParseContent()).execute(response);

}
 
Example #10
Source File: IMSocketManager.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public void packetDispatch(ByteBuf channelBuffer){
    DataBuffer buffer = new DataBuffer(channelBuffer);
    com.mogujie.tt.protobuf.base.Header header = new com.mogujie.tt.protobuf.base.Header();
    header.decode(buffer);
    /**buffer 的指针位于body的地方*/
    int commandId = header.getCommandId();
    int serviceId = header.getServiceId();
    int seqNo = header.getSeqnum();
    logger.d("dispatch packet, serviceId:%d, commandId:%d", serviceId,
            commandId);
    CodedInputStream codedInputStream = CodedInputStream.newInstance(new ByteBufInputStream(buffer.getOrignalBuffer()));

   Packetlistener listener = listenerQueue.pop(seqNo);
   if(listener!=null){
        listener.onSuccess(codedInputStream);
        return;
   }

    // todo eric make it a table
    // 抽象 父类执行
    switch (serviceId){
        case IMBaseDefine.ServiceID.SID_LOGIN_VALUE:
            IMPacketDispatcher.loginPacketDispatcher(commandId,codedInputStream);
            break;
        case IMBaseDefine.ServiceID.SID_BUDDY_LIST_VALUE:
            IMPacketDispatcher.buddyPacketDispatcher(commandId,codedInputStream);
            break;
        case IMBaseDefine.ServiceID.SID_MSG_VALUE:
            IMPacketDispatcher.msgPacketDispatcher(commandId,codedInputStream);
            break;
        case IMBaseDefine.ServiceID.SID_GROUP_VALUE:
            IMPacketDispatcher.groupPacketDispatcher(commandId,codedInputStream);
            break;
        default:
            logger.e("packet#unhandled serviceId:%d, commandId:%d", serviceId,
                    commandId);
            break;
    }
}
 
Example #11
Source File: ReviewInDetailAdapter.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    super.onFailure(statusCode, headers, responseString, throwable);
    dismissProgress();
    Log.d("action ClientCall", throwable + "");
    showToast("Something went wrong.");
}
 
Example #12
Source File: TokenUploadHandler.java    From pusher-websocket-android with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    try {
        String clientId = response.getString("id");
        Log.d(TAG, "Uploaded registration token and received id: " + clientId);
        this.listenerStack.onSuccessfulRegistration(clientId, context);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: TokenUploadHandler.java    From pusher-websocket-android with MIT License 5 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
    String responseString = null;
    if (errorResponse != null) {
        responseString = errorResponse.toString();
    }
    onFailure(statusCode, responseString);
}
 
Example #14
Source File: ReviewsActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
public void onSuccess(int statusCode, Header[] headers, String responseString) {
    super.onSuccess(statusCode, headers, responseString);
    swipeView.setRefreshing(false);
    application.printLog(false, TAG + "-InitCallback-onSuccess", responseString.toString());
    try {
        (new ParseContent()).execute(new JSONObject(responseString));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: SubscriptionChangeHandler.java    From pusher-websocket-android with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    InterestSubscriptionChange change = subscription.getChange();
    InterestSubscriptionChangeListener listener = subscription.getListener();
    String interest = subscription.getInterest();

    Log.d(TAG, "Successfully sent subscription change " + change + " for interest: " + interest);
    if (listener != null) listener.onSubscriptionChangeSucceeded();
}
 
Example #16
Source File: ReviewsActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
    super.onFailure(statusCode, headers, throwable, errorResponse);
    swipeView.setRefreshing(false);
    application.printLog(true, TAG + "-InitCallback-onFailure", throwable.toString());

}
 
Example #17
Source File: ReplyReview.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
    super.onSuccess(statusCode, headers, response);
    dismissProgressDialog();
    showAlert("Reply Posted Successfully.", "OK", null);
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", 1);
    setResult(RESULT_OK, returnIntent);
}
 
Example #18
Source File: ReviewsActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    super.onSuccess(statusCode, headers, response);
    JSONObject data;
    try {
        data = response.getJSONObject("data");
        if (!data.isNull("permissions")) {
            JSONObject permissions = data.getJSONObject("permissions");
            if (!permissions.isNull("moderator_key"))
                application.saveDataInSharedPreferences(
                        LFSAppConstants.ISMOD, "yes");
            else {
                application.saveDataInSharedPreferences(
                        LFSAppConstants.ISMOD, "no");
            }
        } else {
            application.saveDataInSharedPreferences(
                    LFSAppConstants.ISMOD, "no");
        }
        if (!data.isNull("profile")) {
            JSONObject profile = data.getJSONObject("profile");

            if (!profile.isNull("id")) {
                application.saveDataInSharedPreferences(
                        LFSAppConstants.ID, profile.getString("id"));
                adminClintId = profile.getString("id");
            }
        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
    bootstrapClientCall();
}
 
Example #19
Source File: NewActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
    super.onSuccess(statusCode, headers, response);
    dismissProgressDialog();
    showAlert("Reply Posted Successfully.", "OK", null);
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", 1);
    setResult(RESULT_OK, returnIntent);
}
 
Example #20
Source File: ReplyReview.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    super.onSuccess(statusCode, headers, response);
    dismissProgressDialog();
    showAlert("Reply Posted Successfully.", "OK", null);
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", 1);
    setResult(RESULT_OK, returnIntent);
}
 
Example #21
Source File: Helper.java    From KUAS-AP-Material with MIT License 5 votes vote down vote up
private static void onHelperFail(Context context, GeneralCallback callback, int statusCode,
                                 Header[] headers, Throwable throwable, String errorMessage) {
	if (callback != null) {
		if (errorMessage != null && errorMessage.toLowerCase().contains("token expired")) {
			callback.onTokenExpired();
		} else if (statusCode == 0) {
			callback.onFail(context.getString(R.string.timeout_message));
		} else {
			callback.onFail(context.getString(R.string.something_error) + ":" +
					statusCode + (errorMessage == null ? "" : " " + errorMessage));
		}
	}
}
 
Example #22
Source File: CommentActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    super.onFailure(statusCode, headers, responseString, throwable);
    dismissProgressDialog();
    if (throwable != null)
        showToast(throwable.toString());
    else
        showToast("Something went wrong.");
}
 
Example #23
Source File: HtmlUnitBrowserCompatCookieSpec.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
@Override
public List<Header> formatCookies(final List<Cookie> cookies) {
    Collections.sort(cookies, COOKIE_COMPARATOR);

    final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
    buffer.append(SM.COOKIE);
    buffer.append(": ");
    for (int i = 0; i < cookies.size(); i++) {
        final Cookie cookie = cookies.get(i);
        if (i > 0) {
            buffer.append("; ");
        }
        final String cookieName = cookie.getName();
        final String cookieValue = cookie.getValue();
        if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
            HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(
                    buffer,
                    new BasicHeaderElement(cookieName, cookieValue),
                    false);
        }
        else {
            // Netscape style cookies do not support quoted values
            buffer.append(cookieName);
            buffer.append("=");
            if (cookieValue != null) {
                buffer.append(cookieValue);
            }
        }
    }
    final List<Header> headers = new ArrayList<>(1);
    headers.add(new BufferedHeader(buffer));
    return headers;
}
 
Example #24
Source File: AbstractVichanModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String deletePost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    String url = getUsingUrl() + "post.php";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("board", model.boardName));
    pairs.add(new BasicNameValuePair("delete_" + model.postNumber, "on"));
    if (model.onlyFiles) pairs.add(new BasicNameValuePair("file", "on"));
    pairs.add(new BasicNameValuePair("password", model.password));
    pairs.add(new BasicNameValuePair("delete", getDeleteFormValue(model)));
    pairs.add(new BasicNameValuePair("reason", ""));
    
    UrlPageModel refererPage = new UrlPageModel();
    refererPage.type = UrlPageModel.TYPE_THREADPAGE;
    refererPage.chanName = getChanName();
    refererPage.boardName = model.boardName;
    refererPage.threadNumber = model.threadNumber;
    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, buildUrl(refererPage)) };
    HttpRequestModel rqModel = HttpRequestModel.builder().
            setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).setCustomHeaders(customHeaders).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task);
        if (response.statusCode == 200 || response.statusCode == 400 || response.statusCode == 303) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse);
            if (errorMatcher.find()) throw new Exception(errorMatcher.group(1));
            return null;
        }
        throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null) response.release();
    }
}
 
Example #25
Source File: AbstractVichanModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String reportPost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    String url = getUsingUrl() + "post.php";
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("board", model.boardName));
    pairs.add(new BasicNameValuePair("delete_" + model.postNumber, "on"));
    pairs.add(new BasicNameValuePair("password", ""));
    pairs.add(new BasicNameValuePair("reason", model.reportReason));
    pairs.add(new BasicNameValuePair("report", getReportFormValue(model)));
    
    UrlPageModel refererPage = new UrlPageModel();
    refererPage.type = UrlPageModel.TYPE_THREADPAGE;
    refererPage.chanName = getChanName();
    refererPage.boardName = model.boardName;
    refererPage.threadNumber = model.threadNumber;
    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, buildUrl(refererPage)) };
    HttpRequestModel rqModel = HttpRequestModel.builder().
            setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).setCustomHeaders(customHeaders).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task);
        if (response.statusCode == 200 || response.statusCode == 400 || response.statusCode == 303) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            Matcher errorMatcher = ERROR_PATTERN.matcher(htmlResponse);
            if (errorMatcher.find()) throw new Exception(errorMatcher.group(1));
            return null;
        }
        throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null) response.release();
    }
}
 
Example #26
Source File: AbstractKusabaModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    String url = getBoardScriptUrl(model);
    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task);
    setSendPostEntity(model, postEntityBuilder);
    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true).build();
    HttpResponseModel response = null;
    try {
        response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
        if (response.statusCode == 302) {
            for (Header header : response.headers) {
                if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                    return fixRelativeUrl(header.getValue());
                }
            }
        } else if (response.statusCode == 200) {
            ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
            IOUtils.copyStream(response.stream, output);
            String htmlResponse = output.toString("UTF-8");
            Matcher errorMatcher = ERROR_POSTING.matcher(htmlResponse);
            if (errorMatcher.find()) throw new Exception(errorMatcher.group(1).trim());
        } else throw new Exception(response.statusCode + " - " + response.statusReason);
    } finally {
        if (response != null) response.release();
    }
    return null;
}
 
Example #27
Source File: HttpRequestModel.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private HttpRequestModel(
        int method,
        boolean checkIfModified,
        boolean noRedirect,
        Header[] customHeaders,
        HttpEntity postEntity,
        int timeoutValue) {
    this.method = method;
    this.checkIfModified = checkIfModified;
    this.noRedirect = noRedirect;
    this.customHeaders = customHeaders;
    this.postEntity = postEntity;
    this.timeoutValue = timeoutValue;
}
 
Example #28
Source File: EditReview.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
    super.onSuccess(statusCode, headers, responseString);
    Log.d("Log", "" + responseString);
    dismissProgressDialog();
    showAlert("Review Edited Successfully.", "OK", null);
}
 
Example #29
Source File: EditReview.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
    super.onSuccess(statusCode, headers, response);
    Log.d("Log", "" + response);
    dismissProgressDialog();
    showAlert("Review Edited Successfully.", "OK", null);
}
 
Example #30
Source File: CommentsActivity.java    From StreamHub-Android-SDK with MIT License 5 votes vote down vote up
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
    super.onSuccess(statusCode, headers, response);
    Log.d(TAG, "InitCallback-onSuccess: " + response.toString());
    try {
        String responseString = response.toString();
        buildCommentList(responseString);
        swipeView.setRefreshing(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}