org.apache.http.protocol.HTTP Java Examples

The following examples show how to use org.apache.http.protocol.HTTP. 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 Project: hsac-fitnesse-fixtures   Author: fhoeben   File: HttpServer.java    License: Apache License 2.0 7 votes vote down vote up
protected Charset getCharSet(Headers heHeaders) {
    Charset charset = UTF8;
    String contentTypeHeader = heHeaders.getFirst(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset contentTypeCharset = contentType.getCharset();
            if (contentTypeCharset != null) {
                charset = contentTypeCharset;
            }
        } catch (ParseException | UnsupportedCharsetException e) {
            // ignore, use default charset UTF8
        }
    }
    return charset;
}
 
Example #2
Source Project: micro-integrator   Author: wso2   File: InboundHttpServerWorker.java    License: Apache License 2.0 6 votes vote down vote up
private void doPreInjectTasks(MessageContext axis2MsgContext, Axis2MessageContext synCtx, String method) {

        if (!isRESTRequest(axis2MsgContext, method)) {
            if (request.isEntityEnclosing()) {
                processEntityEnclosingRequest(axis2MsgContext, false);
            } else {
                processNonEntityEnclosingRESTHandler(null, axis2MsgContext, false);
            }
        } else {
            AxisOperation axisOperation = synCtx.getAxis2MessageContext().getAxisOperation();
            synCtx.getAxis2MessageContext().setAxisOperation(null);
            String contentTypeHeader = request.getHeaders().get(HTTP.CONTENT_TYPE);
            SOAPEnvelope soapEnvelope = handleRESTUrlPost(contentTypeHeader);
            processNonEntityEnclosingRESTHandler(soapEnvelope, axis2MsgContext, false);
            synCtx.getAxis2MessageContext().setAxisOperation(axisOperation);

        }
    }
 
Example #3
Source Project: Conquer   Author: hanks-zyh   File: NetUtils.java    License: Apache License 2.0 6 votes vote down vote up
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();
	}
}
 
Example #4
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: HttpClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String httpPostWithWCF4Url(String serverUrl, JSONObject params) {
    String responseStr = null;
    try {
        String url = serverUrl;
        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(url);

        System.out.println("toGetString(params):" + toGetString(params));
        request.setEntity(new StringEntity(params.toString(), CODE));

        request.setHeader(HTTP.CONTENT_TYPE, "text/json");
        request.setHeader("Accept", "json");

        HttpResponse response = client.execute(request);

        responseStr = EntityUtils.toString(response.getEntity(), CODE);
        // System.out.println("responseStr:" + responseStr);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseStr;
}
 
Example #5
Source Project: device-database   Author: android-database-best-practices   File: HttpHeaderParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source Project: android-vlc-remote   Author: samicemalone   File: MediaServer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected final <T> T read(ContentHandler handler) throws IOException {
    String spec = mUri.toString();
    URL url = new URL(spec);
    HttpURLConnection http = (HttpURLConnection) url.openConnection();
    http.setConnectTimeout(TIMEOUT);
    try {
        String usernamePassword = mUri.getUserInfo();
        if (usernamePassword != null) {
            Header authorization = BasicScheme.authenticate(
                    new UsernamePasswordCredentials(usernamePassword), HTTP.UTF_8, false);
            http.setRequestProperty(authorization.getName(), authorization.getValue());
        }
        return (T) handler.getContent(http);
    } finally {
        http.disconnect();
    }
}
 
Example #7
Source Project: TitanjumNote   Author: jungletian   File: HttpHeaderParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source Project: data-prep   Author: Talend   File: HttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The connection keep alive strategy.
 */
private ConnectionKeepAliveStrategy getKeepAliveStrategy() {

    return (response, context) -> {
        // Honor 'keep-alive' header
        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 && "timeout".equalsIgnoreCase(param)) {
                try {
                    return Long.parseLong(value) * 1000;
                } catch (NumberFormatException ignore) {
                    // let's move on the next header value
                    break;
                }
            }
        }
        // otherwise use the default value
        return defaultKeepAlive * 1000;
    };
}
 
Example #9
Source Project: Android-Basics-Codes   Author: DuGuQiuBai   File: MySSLSocketFactory.java    License: Artistic License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #10
Source Project: redis-manager   Author: ngbdf   File: HttpClientUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 实例化连接池,设置连接池管理器。
 * 这里需要以参数形式注入上面实例化的连接池管理器
 *
 * @return
 */
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
    HeaderElementIterator it = new BasicHeaderElementIterator(httpResponse.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) {
            }
        }
    }
    return 5 * 1000;
}
 
Example #11
Source Project: volley   Author: bacy   File: HttpHeaderParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the charset specified in the Content-Type of this header,
 * or the HTTP default (UTF_8) 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.UTF_8;
}
 
Example #12
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: HttpClientUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String httpPostWithWCF(String serverUrl, String method,
                                     JSONObject params) {
    String responseStr = null;
    try {
        String url = serverUrl + method;
        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(url);

        request.setEntity(new StringEntity(params.toString(), CODE));
        request.setHeader(HTTP.CONTENT_TYPE, "text/json");

        HttpResponse response = client.execute(request);

        responseStr = EntityUtils.toString(response.getEntity(), CODE);
        // System.out.println("responseStr:" + responseStr);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseStr;
}
 
Example #13
Source Project: PoseidonX   Author: ucarGroup   File: HttpSendClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个{@link HttpSendClient} 实例
 * <p>
 * 多态
 * 
 * @return
 */
public HttpSendClient newHttpSendClient() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeOut());
    HttpConnectionParams.setSoTimeout(params, getSoTimeOut());
    // HttpConnectionParams.setLinger(params, 1);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // 解释: 握手的目的,是为了允许客户端在发送请求内容之前,判断源服务器是否愿意接受请求(基于请求头部)。
    // Expect:100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题。
    // 默认开启
    // HttpProtocolParams.setUseExpectContinue(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, getSocketBufferSize());

    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
    threadSafeClientConnManager.setMaxTotal(getMaxTotalConnections());
    threadSafeClientConnManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(getRetryCount(), false);

    DefaultHttpClient httpClient = new DefaultHttpClient(threadSafeClientConnManager, params);
    httpClient.setHttpRequestRetryHandler(retryHandler);
    return new HttpSendClient(httpClient);
}
 
Example #14
Source Project: android-advanced-light   Author: henrymorgen   File: MainActivity.java    License: MIT License 6 votes vote down vote up
/**
 * 设置默认请求参数,并返回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;

}
 
Example #15
Source Project: BigApp_Discuz_Android   Author: BigAppOS   File: MultipartEntity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source Project: cyberduck   Author: iterate-ch   File: DelayedHttpMultipartEntity.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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();
}
 
Example #17
Source Project: wakao-app   Author: yongbo000   File: MyRobot.java    License: MIT License 6 votes vote down vote up
public String postDataToServer(List<NameValuePair> nvs, String url, String cookie) {
	DefaultHttpClient httpclient = new DefaultHttpClient();
	HttpPost httpost = new HttpPost(url);
	httpost.setHeader("Cookie", cookie);
	StringBuilder sb = new StringBuilder();
	// 设置表单提交编码为UTF-8
	try {
		httpost.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
		HttpResponse response = httpclient.execute(httpost);
		HttpEntity entity = response.getEntity();
		InputStreamReader isr = new InputStreamReader(entity.getContent());
		BufferedReader bufReader = new BufferedReader(isr);
		String lineText = null;
		while ((lineText = bufReader.readLine()) != null) {
			sb.append(lineText);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		httpclient.getConnectionManager().shutdown();
	}
	return sb.toString();
}
 
Example #18
Source Project: Android-Commons   Author: delight-im   File: Social.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Displays an application chooser and composes the described text message (SMS) using the selected application
 *
 * @param recipientPhone the recipient's phone number or `null`
 * @param bodyText the body text of the message
 * @param captionRes a string resource ID for the title of the application chooser's window
 * @param context a context reference
 * @throws Exception if there was an error trying to launch the SMS application
 */
public static void sendSms(final String recipientPhone, final String bodyText, final int captionRes, final Context context) throws Exception {
	final Intent intent = new Intent(Intent.ACTION_SENDTO);
	intent.setType(HTTP.PLAIN_TEXT_TYPE);

	if (recipientPhone != null && recipientPhone.length() > 0) {
		intent.setData(Uri.parse("smsto:"+recipientPhone));
	}
	else {
		intent.setData(Uri.parse("sms:"));
	}

	intent.putExtra("sms_body", bodyText);
	intent.putExtra(Intent.EXTRA_TEXT, bodyText);

	if (context != null) {
		// offer a selection of all applications that can handle the SMS Intent
		context.startActivity(Intent.createChooser(intent, context.getString(captionRes)));
	}
}
 
Example #19
Source Project: fanfouapp-opensource   Author: mcxiaoke   File: NetworkHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static final HttpParams createHttpParams() {
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ConnManagerParams.setTimeout(params, NetworkHelper.SOCKET_TIMEOUT_MS);
    HttpConnectionParams.setConnectionTimeout(params,
            NetworkHelper.CONNECTION_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params,
            NetworkHelper.SOCKET_TIMEOUT_MS);

    ConnManagerParams.setMaxConnectionsPerRoute(params,
            new ConnPerRouteBean(NetworkHelper.MAX_TOTAL_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(params,
            NetworkHelper.MAX_TOTAL_CONNECTIONS);

    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params,
            NetworkHelper.SOCKET_BUFFER_SIZE);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "FanFou for Android/"
            + AppContext.appVersionName);
    return params;
}
 
Example #20
Source Project: AppServiceRestFul   Author: wanliyang1990   File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
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(); 
   } 
}
 
Example #21
Source Project: Mobike   Author: yiwent   File: MySSLSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #22
Source Project: io   Author: fujitsu-pio   File: ReadTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);

    DcResponse 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();
}
 
Example #23
Source Project: barterli_android   Author: barterli   File: HurlStack.java    License: Apache License 2.0 6 votes vote down vote up
private static void addBodyIfExists(HttpURLConnection connection,
                Request<?> request) throws IOException, AuthFailureError {

    byte[] body = request.getBody();
    if (body != null) {
        if (VolleyLog.sDebug) {
            VolleyLog.v("Request url: %s\nBody: %s", request.getUrl(), new String(body, HTTP.UTF_8));
        }
        connection.setDoOutput(true);
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request
                        .getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}
 
Example #24
Source Project: barterli_android   Author: barterli   File: StringPart.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param name String - name of parameter (may not be <code>null</code>).
 * @param value String - value of parameter (may not be <code>null</code>).
 * @param charset String, if null is passed then default "ISO-8859-1" charset is used.
 * 
 * @throws IllegalArgumentException if either <code>value</code> 
 *         or <code>name</code> is <code>null</code>.
 * @throws RuntimeException if <code>charset</code> is unsupported by OS.
 */
public StringPart(String name, String value, String charset) {
    if (name == null) {
        throw new IllegalArgumentException("Name may not be null");     //$NON-NLS-1$
    }
    if (value == null) {
        throw new IllegalArgumentException("Value may not be null");    //$NON-NLS-1$
    }
    
    final String partName = UrlEncodingHelper.encode(name, HTTP.DEFAULT_PROTOCOL_CHARSET);
    
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }
    final String partCharset = charset;
    
    try {
        this.valueBytes = value.getBytes(partCharset);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    
    headersProvider = new IHeadersProvider() {
        public String getContentDisposition() {
            return "Content-Disposition: form-data; name=\"" + partName + '"';                  //$NON-NLS-1$
        }
        public String getContentType() {
            return "Content-Type: " + HTTP.PLAIN_TEXT_TYPE + HTTP.CHARSET_PARAM + partCharset;  //$NON-NLS-1$
        }
        public String getContentTransferEncoding() {
            return "Content-Transfer-Encoding: 8bit";                                           //$NON-NLS-1$
        }
    };
}
 
Example #25
Source Project: micro-integrator   Author: wso2   File: SwaggerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update the response with provided response string.
 *
 * @param response       CarbonHttpResponse which will be updated
 * @param responseString String response to be updated in response
 * @param contentType    Content type of the response to be updated in response headaers
 * @throws Exception Any exception occured during the update
 */
protected void updateResponse(CarbonHttpResponse response, String responseString, String contentType) throws
        AxisFault {
    try {
        ((BlobOutputStream) response.getOutputStream()).getBlob().readFrom(new ByteArrayInputStream
                (responseString.getBytes(SwaggerConstants.DEFAULT_ENCODING)), responseString.length());
    } catch (StreamCopyException streamCopyException) {
        handleException("Error in generating Swagger definition : failed to copy data to response ",
                streamCopyException);
    } catch (UnsupportedEncodingException encodingException) {
        handleException("Error in generating Swagger definition : exception in encoding ", encodingException);
    }
    response.setStatus(SwaggerConstants.HTTP_OK);
    response.getHeaders().put(HTTP.CONTENT_TYPE, contentType);
}
 
Example #26
Source Project: pinpoint   Author: naver   File: HttpClient4EntityExtractor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * copy: EntityUtils Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used.
 *
 * @param entity         must not be null
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String. May be null if {@link HttpEntity#getContent()} is null.
 * @throws ParseException           if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException              if an error occurs reading the input stream
 */
@SuppressWarnings("deprecation")
private static String entityUtilsToString(final HttpEntity entity, final String defaultCharset, final int maxLength) throws Exception {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity must not be null");
    }
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        return "HTTP entity is too large to be buffered in memory length:" + entity.getContentLength();
    }
    if (entity.getContentType().getValue().startsWith("multipart/form-data")) {
        return "content type is multipart/form-data. content length:" + entity.getContentLength();
    }

    String charset = getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    final FixedByteArrayOutputStream outStream = new FixedByteArrayOutputStream(maxLength);
    entity.writeTo(outStream);
    final String entityValue = outStream.toString(charset);
    if (entity.getContentLength() > maxLength) {
        final StringBuilder sb = new StringBuilder();
        sb.append(entityValue);
        sb.append("HTTP entity large length: ");
        sb.append(entity.getContentLength());
        sb.append(" )");
        return sb.toString();
    }

    return entityValue;
}
 
Example #27
Source Project: fanfouapp-opensource   Author: mcxiaoke   File: ApiClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public User friendshipsDelete(final String userId, final String mode)
        throws ApiException {
    if (TextUtils.isEmpty(userId)) {
        throw new NullPointerException(
                "friendshipsDelete() userId must not be empty or null.");
    }
    // String url=String.format(URL_FRIENDSHIPS_DESTROY, userId);
    String url;
    try {
        url = String.format(ApiConfig.URL_FRIENDSHIPS_DESTROY,
                URLEncoder.encode(userId, HTTP.UTF_8));
    } catch (final UnsupportedEncodingException e) {
        url = String.format(ApiConfig.URL_FRIENDSHIPS_DESTROY, userId);
    }

    final SimpleResponse response = doPostIdAction(url, null, null, mode);
    final int statusCode = response.statusCode;
    if (AppContext.DEBUG) {
        log("friendshipsDelete()---statusCode=" + statusCode + " url="
                + url);
    }
    final User u = User.parse(response);
    if (u != null) {
        u.ownerId = AppContext.getUserId();
        CacheManager.put(u);
    }
    return u;
}
 
Example #28
Source Project: arangodb-java-driver   Author: arangodb   File: HttpConnection.java    License: Apache License 2.0 5 votes vote down vote up
private long getKeepAliveDuration(final HttpResponse response) {
    final HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        final HeaderElement he = it.nextElement();
        final String param = he.getName();
        final String value = he.getValue();
        if (value != null && "timeout".equalsIgnoreCase(param)) {
            try {
                return Long.parseLong(value) * 1000L;
            } catch (final NumberFormatException ignore) {
            }
        }
    }
    return 30L * 1000L;
}
 
Example #29
Source Project: DataSphereStudio   Author: WeBankFinTech   File: HttpTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test07() throws IOException {
    Cookie cookie = test01();
    String projectName = "create_project0930";
    HttpPost httpPost = new HttpPost("http://127.0..0.1:8290/manager" + "?project=" + projectName);
    httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
    CloseableHttpResponse response = null;
    File file = new File("E:\\appcom\\tmp\\dws\\wtss\\neiljianliu\\2019-09-30\\project_0926_tjf.zip");
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);
    CloseableHttpClient httpClient = null;
    InputStream inputStream = null;
    try {
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        MultipartEntityBuilder entityBuilder =  MultipartEntityBuilder.create();
        entityBuilder.addBinaryBody("file",file);
        entityBuilder.addTextBody("ajax", "upload");
        entityBuilder.addTextBody("project", projectName);
        httpPost.setEntity(entityBuilder.build());
        response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        inputStream = httpEntity.getContent();
        String entStr = null;
        entStr = IOUtils.toString(inputStream, "utf-8");
        if(response.getStatusLine().getStatusCode() != 200){
            throw new SchedulisServerException(90005, "release project failed, " + entStr);
        }
    }catch (Exception e){
        System.out.println(e.getMessage());
    }
    finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(httpClient);
    }
}
 
Example #30
Source Project: carbon-identity   Author: wso2-attic   File: ServerUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param entity
 * @return
 * @throws IOException
 * @throws ParseException
 */
public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    if (instream == null) {
        return "";
    }
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(

                "HTTP entity too large to be buffered in memory");
    }
    String charset = getContentCharSet(entity);
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }
    Reader reader = new InputStreamReader(instream, charset);
    StringBuilder buffer = new StringBuilder();
    try {
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}