private static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
public static String getFileNameFromHttpResponse(final HttpResponse response) { if (response == null) return null; String result = null; Header header = response.getFirstHeader("Content-Disposition"); if (header != null) { for (HeaderElement element : header.getElements()) { NameValuePair fileNamePair = element.getParameterByName("filename"); if (fileNamePair != null) { result = fileNamePair.getValue(); // try to get correct encoding str result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length()); break; } } } return result; }
/** * Retrieve a charset from headers * * @param headers An {@link java.util.Map} of headers * @param defaultCharset Charset to return if none can be found * @return Returns the charset specified in the Content-Type of this header, * or the defaultCharset if none can be found. */ public static String parseCharset(Map<String, String> headers, String defaultCharset) { String contentType = headers.get(HTTP.CONTENT_TYPE); if (contentType != null) { String[] params = contentType.split(";"); for (int i = 1; i < params.length; i++) { String[] pair = params[i].trim().split("="); if (pair.length == 2) { if (pair[0].equals("charset")) { return pair[1]; } } } } return defaultCharset; }
/** * Retrieve a charset from headers * * @param headers An {@link Map} of headers * @param defaultCharset Charset to return if none can be found * @return Returns the charset specified in the Content-Type of this header, * or the defaultCharset if none can be found. */ public static String parseCharset(Map<String, String> headers, String defaultCharset) { String contentType = headers.get(HTTP.CONTENT_TYPE); if (contentType != null) { String[] params = contentType.split(";"); for (int i = 1; i < params.length; i++) { String[] pair = params[i].trim().split("="); if (pair.length == 2) { if (pair[0].equals("charset")) { return pair[1]; } } } } return defaultCharset; }
/** * 设置默认请求参数,并返回HttpClient * * @return HttpClient */ private HttpClient createHttpClient() { HttpParams mDefaultHttpParams = new BasicHttpParams(); //设置连接超时 HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000); //设置请求超时 HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000); HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true); HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8); //持续握手 HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true); HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams); return mHttpClient; }
/** * Build the HttpEntity to be sent to the Service as part of (POST) request. Creates a off-memory * {@link FileExposingFileEntity} or a regular in-memory {@link ByteArrayEntity} depending on if the request * OutputStream fit into memory when built by calling. * * @param request - * @return - the built HttpEntity * @throws IOException - */ protected HttpEntity buildEntity(final ClientInvocation request) throws IOException { HttpEntity entityToBuild = null; DeferredFileOutputStream memoryManagedOutStream = writeRequestBodyToOutputStream(request); if (memoryManagedOutStream.isInMemory()) { ByteArrayEntity entityToBuildByteArray = new ByteArrayEntity(memoryManagedOutStream.getData()); entityToBuildByteArray.setContentType( new BasicHeader(HTTP.CONTENT_TYPE, request.getHeaders().getMediaType().toString())); entityToBuild = entityToBuildByteArray; } else { File requestBodyFile = memoryManagedOutStream.getFile(); requestBodyFile.deleteOnExit(); entityToBuild = new FileExposingFileEntity( memoryManagedOutStream.getFile(), request.getHeaders().getMediaType().toString()); } return entityToBuild; }
/** * Gets getUrl DefaultHttpClient which trusts getUrl set of certificates specified by the KeyStore * * @param keyStore custom provided KeyStore instance * @return DefaultHttpClient */ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
@Deprecated public static String post(String Url, List<NameValuePair> params) { String strResult = null; HttpResponse httpResponse; HttpPost httpRequest = new HttpPost(Url); try { httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { strResult = EntityUtils.toString(httpResponse.getEntity()); } } catch (Exception e) { e.printStackTrace(); } return strResult; }
@Override public void send(CrashReportData report) throws ReportSenderException { String log = createCrashLog(report); String url = BASE_URL + ACRA.getConfig().formKey() + CRASHES_PATH; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("raw", log)); parameters.add(new BasicNameValuePair("userID", report.get(ReportField.INSTALLATION_ID))); parameters.add(new BasicNameValuePair("contact", report.get(ReportField.USER_EMAIL))); parameters.add(new BasicNameValuePair("description", report.get(ReportField.USER_COMMENT))); httpPost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); httpClient.execute(httpPost); } catch (Exception e) { e.printStackTrace(); } }
/** * Creates an instance using the specified parameters * * @param mode the mode to use, may be {@code null}, in which case {@link HttpMultipartMode#STRICT} is used * @param boundary the boundary string, may be {@code null}, in which case {@link #generateBoundary()} is invoked to create the string * @param charset the character set to use, may be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. UTF-8 - is used. */ public MultipartEntity( HttpMultipartMode mode, String boundary, Charset charset) { super(); if (boundary == null) { boundary = generateBoundary(); } this.boundary = boundary; if (mode == null) { mode = HttpMultipartMode.STRICT; } this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET; this.multipart = new HttpMultipart(multipartSubtype, this.charset, this.boundary, mode); this.contentType = new BasicHeader( HTTP.CONTENT_TYPE, generateContentType(this.boundary, this.charset)); this.dirty = true; }
@Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { long timeout = Long.parseLong(value) * 1000; if (timeout > 20 * 1000) { return 20 * 1000; } else { return timeout; } } } return 5 * 1000; }
/** * Cell取得した場合にatomフォーマットでレスポンスが返却されること. $format → なし Accept → application/atom+xml */ @Test public final void acceptがatomでCell取得した場合にatomフォーマットでレスポンスが返却されること() { String url = getUrl(this.cellId); // $format なし // Acceptヘッダ application/atom+xml HashMap<String, String> headers = new HashMap<String, String>(); headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_ATOM_XML); this.setHeaders(headers); PersoniumResponse res = this.restGet(url); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); this.responseHeaderMap.put(HTTP.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); this.checkHeaders(res); // Etagのチェック assertEquals(1, res.getResponseHeaders(HttpHeaders.ETAG).length); res.bodyAsXml(); }
/** * Cell取得した場合にatomフォーマットでレスポンスが返却されること. $format → atom Accept → application/atom+xml */ @Test public final void $formatがatomかつacceptがjsonでCell取得した場合にatomフォーマットでレスポンスが返却されること() { String url = getUrl(this.cellId); // $format atom // Acceptヘッダ application/json HashMap<String, String> headers = new HashMap<String, String>(); headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); this.setHeaders(headers); PersoniumResponse res = this.restGet(url + "?" + QUERY_FORMAT_ATOM); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); this.responseHeaderMap.put(HTTP.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); this.checkHeaders(res); // Etagのチェック assertEquals(1, res.getResponseHeaders(HttpHeaders.ETAG).length); res.bodyAsXml(); }
/** * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an * {@link HttpEntity}. The encoding is taken from the entity's * Content-Encoding header. * <p> * This is typically used while parsing an HTTP POST. * * @param entity * The entity to parse * @throws IOException * If there was an exception getting the entity's data. */ public static List <NameValuePair> parse ( final HttpEntity entity) throws IOException { ContentType contentType = ContentType.get(entity); if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) { String content = EntityUtils.toString(entity, Consts.ASCII); if (content != null && content.length() > 0) { Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return parse(content, charset); } } return Collections.emptyList(); }
/** * Acceptに空文字を指定してCell取得した場合にatomフォーマットでレスポンスが返却されること. $format → atom Accept → application/atom+xml */ @Test public final void $formatがatomでacceptが空文字でCell取得した場合にatomフォーマットでレスポンスが返却されること() { String url = getUrl(this.cellId); // $format atom // Acceptヘッダ 空文字 HashMap<String, String> headers = new HashMap<String, String>(); headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); headers.put(HttpHeaders.ACCEPT, ""); this.setHeaders(headers); PersoniumResponse res = restGet(url + "?" + QUERY_FORMAT_ATOM); // TODO Acceptヘッダーのチェック処理が完了したら、NOT_ACCEPTABLEのチェックに変更する assertEquals(HttpStatus.SC_OK, res.getStatusCode()); this.responseHeaderMap.put(HTTP.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); this.checkHeaders(res); // Etagのチェック assertEquals(1, res.getResponseHeaders(HttpHeaders.ETAG).length); res.bodyAsXml(); }
private static String httpPush (ArrayList<NameValuePair> nameValuePairs,String action) throws Exception { HttpPost httppost = new HttpPost(FLOWZR_API_URL + nsString + "/" + action + "/"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); HttpResponse response; String strResponse; response = http_client.execute(httppost); HttpEntity entity = response.getEntity(); int code = response.getStatusLine().getStatusCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); strResponse = reader.readLine(); entity.consumeContent(); if (code!=200) { throw new Exception(Html.fromHtml(strResponse).toString()); } return strResponse; }
/** * Creates a StringEntity with the specified content and content type. * * @param string content to be used. Not {@code null}. * @param contentType content type to be used. May be {@code null}, in which case the default * MIME type {@link ContentType#TEXT_PLAIN} is assumed. * * @throws IllegalArgumentException if the string parameter is null * * @since 4.2 */ public StringEntity(final String string, final ContentType contentType) { super(); if (string == null) { throw new IllegalArgumentException("Source string may not be null"); } Charset charset = contentType != null ? contentType.getCharset() : null; if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } try { this.content = string.getBytes(charset.name()); } catch (UnsupportedEncodingException ex) { // should never happen throw new UnsupportedCharsetException(charset.name()); } if (contentType != null) { setContentType(contentType.toString()); } }
/** * Creates a StringEntity with the specified content, MIME type and charset * * @param string content to be used. Not {@code null}. * @param mimeType MIME type to be used. May be {@code null}, in which case the default * is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" * @param charset character set to be used. May be {@code null}, in which case the default * is {@link HTTP#DEF_CONTENT_CHARSET} i.e. "ISO-8859-1" * * @since 4.1 * @throws IllegalArgumentException if the string parameter is null * * @deprecated (4.1.3) use {@link #StringEntity(String, ContentType)} */ @Deprecated public StringEntity(final String string, String mimeType, String charset) throws UnsupportedEncodingException { super(); if (string == null) { throw new IllegalArgumentException("Source string may not be null"); } if (mimeType == null) { mimeType = HTTP.PLAIN_TEXT_TYPE; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } this.content = string.getBytes(charset); setContentType(mimeType + HTTP.CHARSET_PARAM + charset); }
/** * Returns a substring of this buffer with leading and trailing whitespace * omitted. The substring begins with the first non-whitespace character * from <code>beginIndex</code> and extends to the last * non-whitespace character with the index lesser than * <code>endIndex</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of this * buffer, or <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substringTrimmed(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex); } while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) { beginIndex++; } while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) { endIndex--; } return new String(this.buffer, beginIndex, endIndex - beginIndex); }
/** * Reads a complete line of characters up to a line delimiter from this * session buffer. The line delimiter itself is discarded. If no char is * available because the end of the stream has been reached, * <code>null</code> is returned. This method blocks until input data is * available, end of file is detected, or an exception is thrown. * <p> * This method treats a lone LF as a valid line delimiters in addition * to CR-LF required by the HTTP specification. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ private int lineFromLineBuffer(final CharArrayBuffer charbuffer) throws IOException { // discard LF if found int len = this.linebuffer.length(); if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { len--; } // discard CR if found if (len > 0) { if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { len--; } } } if (this.ascii) { charbuffer.append(this.linebuffer, 0, len); } else { ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); len = appendDecoded(charbuffer, bbuf); } this.linebuffer.clear(); return len; }
private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) throws IOException { int off = this.bufferpos; int len; this.bufferpos = pos + 1; if (pos > off && this.buffer[pos - 1] == HTTP.CR) { // skip CR if found pos--; } len = pos - off; if (this.ascii) { charbuffer.append(this.buffer, off, len); } else { ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); len = appendDecoded(charbuffer, bbuf); } return len; }
@Override public HttpResponseOutputStream<String> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final List<Header> headers = new ArrayList<Header>(); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); // Content-Range entity-header is sent with a partial entity-body to specify where // in the full entity-body the partial body should be applied. final String header = String.format("bytes %d-%d/%d", range.getStart(), range.getEnd(), status.getOffset() + status.getLength()); if(log.isDebugEnabled()) { log.debug(String.format("Add range header %s for file %s", header, file)); } headers.add(new BasicHeader(HttpHeaders.CONTENT_RANGE, header)); } if(expect) { if(status.getLength() > 0L) { headers.add(new BasicHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE)); } } return this.write(file, headers, status); }
/** * @param status Length */ public DelayedHttpMultipartEntity(final String filename, final TransferStatus status, final String boundary) { this.status = status; final StringBuilder multipartHeader = new StringBuilder(); multipartHeader.append(TWO_DASHES); multipartHeader.append(boundary); multipartHeader.append(CR_LF); multipartHeader.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", filename)); multipartHeader.append(CR_LF); multipartHeader.append(String.format("%s: %s", HTTP.CONTENT_TYPE, StringUtils.isBlank(status.getMime()) ? MimeTypeService.DEFAULT_CONTENT_TYPE : status.getMime())); multipartHeader.append(CR_LF); multipartHeader.append(CR_LF); header = encode(MIME.DEFAULT_CHARSET, multipartHeader.toString()).buffer(); final StringBuilder multipartFooter = new StringBuilder(); multipartFooter.append(CR_LF); multipartFooter.append(TWO_DASHES); multipartFooter.append(boundary); multipartFooter.append(TWO_DASHES); multipartFooter.append(CR_LF); footer = encode(MIME.DEFAULT_CHARSET, multipartFooter.toString()).buffer(); }
/** * Returns the charset specified in the Content-Type of this header, * or the HTTP default (ISO-8859-1) if none can be found. */ public static String parseCharset(Map<String, String> headers) { String contentType = headers.get(HTTP.CONTENT_TYPE); if (contentType != null) { String[] params = contentType.split(";"); for (int i = 1; i < params.length; i++) { String[] pair = params[i].trim().split("="); if (pair.length == 2) { if (pair[0].equals("charset")) { return pair[1]; } } } } return HTTP.DEFAULT_CONTENT_CHARSET; }
/** * send current ip to server */ private String ipSend() throws Exception { HttpClient ip_send = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/UploadIP"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id))); params.add(new BasicNameValuePair("ip", ip)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = ip_send.execute(post); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int ip_save = jsonObject.getInt("ip_save"); if (ip_save == 1) { return "SUCCESS"; } else return "FAIL"; } return "401 UNAUTHORIZED"; }
public static String register(String email_addr, String nick_name, String pwd) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/Register"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("email_addr", email_addr)); params.add(new BasicNameValuePair("nick_name", nick_name)); params.add(new BasicNameValuePair("pwd", pwd)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int register_status = jsonObject.getInt("register_status"); int user_id = jsonObject.getInt("user_id"); if (register_status == 1) return "SUCCESS,your user_id is " + String.valueOf(user_id); else return "FAIL"; } return "401 UNAUTHORIZED"; }
public static String active(int user_id, String verification_code) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/Active"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); params.add(new BasicNameValuePair("verification_code", verification_code)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int email_verification = jsonObject.getInt("email_verification"); if (email_verification == 1) return "SUCCESS"; else return "FAIL"; } return "401 UNAUTHORIZED"; }
public static String resetPwd(int user_id, String pwd) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/ResetPwd"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); params.add(new BasicNameValuePair("pwd", pwd)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int pwd_reset = jsonObject.getInt("pwd_reset"); if (pwd_reset == 1) return "SUCCESS"; else return "FAIL"; } return "401 UNAUTHORIZED"; }
public String machine_offline(String machine_id) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/machine_offline"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", machine_id)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int status = jsonObject.getInt("status"); if (status == 1) return "SUCCESS"; else return "FAIL"; } return "401 UNAUTHORIZED"; }
public String update_online_time(int machine_id, int user_id, int delta) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/update_online_time"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id))); params.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); params.add(new BasicNameValuePair("delta", String.valueOf(delta))); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 权限通过 return "AUTHORIZED"; } return "401 UNAUTHORIZED"; }
/** * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore * * @param keyStore custom provided KeyStore instance * @return DefaultHttpClient */ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
/** * Acceptに空文字を指定してCell取得した場合にXMLでレスポンスが返却されること. $format → なし Accept → 空文字 */ @Test public final void acceptが空文字でCell取得した場合にXMLでレスポンスが返却されること() { String url = getUrl(this.cellId); // $format なし // Acceptヘッダ 空文字 HashMap<String, String> headers = new HashMap<String, String>(); headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); headers.put(HttpHeaders.ACCEPT, ""); this.setHeaders(headers); PersoniumResponse res = restGet(url); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); this.responseHeaderMap.put(HTTP.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); this.checkHeaders(res); // Etagのチェック assertEquals(1, res.getResponseHeaders(HttpHeaders.ETAG).length); // レスポンスボディのパース res.bodyAsXml(); }
public HttpClient getHttpClient() { if (httpClient == null) { synchronized (this) { if (httpClient == null) { if (pool == null) { //初始化pool try { afterPropertiesSet(); } catch (Exception e) { logger.error(e.getMessage(), e); } } HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(pool); httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(conntimeout).setSocketTimeout(sotimeout).build()); httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } // 否则保持活动5秒 return 5 * 1000; } }); httpClient = httpClientBuilder.build(); } } } return httpClient; }
/** * 设置请求头 * * @author gaoxianglong */ public static void setHeader(HttpRequestBase request, String headers, ContentType contentType, String charset) { if (null == request) { return; } request.setHeader(HTTP.CONTENT_TYPE, Optional.ofNullable(contentType.type).orElseGet(() -> ContentType.APPLICATION_XML.type) + ";" + Optional.ofNullable(charset).orElseGet(() -> "UTF-8")); if (!StringUtils.isEmpty(headers)) { /* 设置请求头参数 */ JSONObject jsonObj = JSONObject.parseObject(JSONObject.parseObject(headers).get("header").toString()); jsonObj.keySet().stream().forEach(key -> request.setHeader(key, jsonObj.getString(key))); } }