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 File: HttpServer.java    From hsac-fitnesse-fixtures with 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 File: HttpSendClientFactory.java    From PoseidonX with 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 #3
Source File: Util.java    From AppServiceRestFul with 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 #4
Source File: InboundHttpServerWorker.java    From micro-integrator with 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 #5
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with 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 #6
Source File: ReadTest.java    From io with 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 #7
Source File: HurlStack.java    From barterli_android with 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 #8
Source File: NetUtils.java    From Conquer with 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 #9
Source File: StringPart.java    From barterli_android with 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 #10
Source File: MySSLSocketFactory.java    From Mobike with 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 #11
Source File: HttpHeaderParser.java    From device-database with 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 #12
Source File: NetworkHelper.java    From fanfouapp-opensource with 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 #13
Source File: Social.java    From Android-Commons with 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 #14
Source File: HttpHeaderParser.java    From TitanjumNote with 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 #15
Source File: DelayedHttpMultipartEntity.java    From cyberduck with 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 #16
Source File: MultipartEntity.java    From BigApp_Discuz_Android with 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 #17
Source File: HttpClient.java    From data-prep with 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 #18
Source File: MainActivity.java    From android-advanced-light with 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 #19
Source File: MySSLSocketFactory.java    From Android-Basics-Codes with 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 #20
Source File: HttpClientUtil.java    From redis-manager with 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 #21
Source File: MyRobot.java    From wakao-app with 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 #22
Source File: HttpHeaderParser.java    From volley with 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 #23
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with 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 #24
Source File: MediaServer.java    From android-vlc-remote with 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 #25
Source File: SDKConnection.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public String GET(String url) {
	if (this.debug) {
		System.out.println("GET: " + url);
	}
	String xml = null;
	try {
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet, localContext);
		HttpEntity entity = response.getEntity();
		xml = EntityUtils.toString(entity, HTTP.UTF_8);

		if (response.getStatusLine().getStatusCode() != 200) {
			this.exception = new SDKException(""
			   + response.getStatusLine().getStatusCode()
			   + " : " + xml);
			return "";
		}
	} catch (Exception exception) {
		if (this.debug) {
			exception.printStackTrace();
		}
		this.exception = new SDKException(exception);
		throw this.exception;
	}
	return xml;
}
 
Example #26
Source File: Social.java    From Android-Commons with Apache License 2.0 5 votes vote down vote up
/**
 * Displays an application chooser and shares the specified plain text and subject line using the selected application
 *
 * @param context a context reference
 * @param windowTitle the title for the application chooser's window
 * @param bodyTextToShare the body text to be shared
 * @param subjectTextToShare the title or subject for the message to be shared, if supported by the target application
 */
public static void shareText(final Context context, final String windowTitle, final String bodyTextToShare, final String subjectTextToShare) {
	final Intent intentInvite = new Intent(Intent.ACTION_SEND);
	intentInvite.setType(HTTP.PLAIN_TEXT_TYPE);
	intentInvite.putExtra(Intent.EXTRA_SUBJECT, subjectTextToShare);
	intentInvite.putExtra(Intent.EXTRA_TEXT, bodyTextToShare);

	context.startActivity(Intent.createChooser(intentInvite, windowTitle));
}
 
Example #27
Source File: RequestProtocolCompliance.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private void addContentTypeHeaderIfMissing(
		HttpEntityEnclosingRequest request) {
	if (request.getEntity().getContentType() == null) {
		((AbstractHttpEntity) request.getEntity())
				.setContentType(HTTP.OCTET_STREAM_TYPE);
	}
}
 
Example #28
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
static HttpPost form(String path, @Nullable Charset charset, String... kv) {
    final HttpPost req = (HttpPost) request(HttpMethod.POST, path, MediaType.FORM_DATA.toString());

    final List<NameValuePair> params = new ArrayList<>();
    for (int i = 0; i < kv.length; i += 2) {
        params.add(new BasicNameValuePair(kv[i], kv[i + 1]));
    }
    // HTTP.DEF_CONTENT_CHARSET = ISO-8859-1
    final Charset encoding = charset == null ? HTTP.DEF_CONTENT_CHARSET : charset;
    final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, encoding);
    req.setEntity(entity);
    return req;
}
 
Example #29
Source File: SDKConnection.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public String GET(String url) {
	if (this.debug) {
		System.out.println("GET: " + url);
	}
	String xml = null;
	try {
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet, localContext);
		HttpEntity entity = response.getEntity();
		xml = EntityUtils.toString(entity, HTTP.UTF_8);

		if (response.getStatusLine().getStatusCode() != 200) {
			this.exception = new SDKException(""
			   + response.getStatusLine().getStatusCode()
			   + " : " + xml);
			return "";
		}
	} catch (Exception exception) {
		if (this.debug) {
			exception.printStackTrace();
		}
		this.exception = new SDKException(exception);
		throw this.exception;
	}
	return xml;
}
 
Example #30
Source File: LightNetwork.java    From light-novel-library_Wenku8_Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * LightHttpPost:
 * 
 * Simple http post function, give url and NVP to get result from server
 * 
 * @param URL
 *            : base url to post
 * @param params
 *            : post content NVP
 * @return: return correct bytes or null
 */
public static byte[] LightHttpPost(String URL, List<NameValuePair> params) {
	// Post transfer through NameValuePair[ ] array
	// on server: request.getParameter("name")
	// List<NameValuePair> params = new ArrayList<NameValuePair>();
	// params.add(new BasicNameValuePair("name", "this is post"));

	HttpPost httpRequest = new HttpPost(URL);
	Log.v("MewX-Net", "In LightHttpPost");
	try {

		// send HTTP request
		httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		Log.v("MewX-Net", "httpRequest.");
		// get HTTP response
		HttpResponse httpResponse = new DefaultHttpClient()
				.execute(httpRequest);
		Log.v("MewX-Net", "httpResponse.");

		// if status code is 200, that's ok
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			Log.v("MewX-Net", "httpResponse.StatusCode == 200");
			// get result byte!!! CANNOT just get String, I need raw bytes
			byte[] strResult = EntityUtils.toByteArray(httpResponse
					.getEntity());
			Log.v("MewX-Net", new String(strResult, "utf-8"));
			return strResult;
		} else {
			Log.v("MewX-Net", "Error Response"
					+ httpResponse.getStatusLine().toString());
			return null;
		}
	} catch (Exception e) {
		Log.v("MewX-Net", e.getMessage());
		e.printStackTrace();
		return null;
	}
}