org.apache.http.HttpVersion Java Examples

The following examples show how to use org.apache.http.HttpVersion. 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: DownloaderWebClientTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBusinessObjectDataAssertNoAuthorizationHeaderWhenNoSsl() throws Exception
{
    HttpClientOperations mockHttpClientOperations = mock(HttpClientOperations.class);
    HttpClientOperations originalHttpClientOperations = (HttpClientOperations) ReflectionTestUtils.getField(downloaderWebClient, "httpClientOperations");
    ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", mockHttpClientOperations);

    try
    {
        CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
        when(mockHttpClientOperations.execute(any(), any())).thenReturn(closeableHttpResponse);

        when(closeableHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
        when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity(xmlHelper.objectToXml(new BusinessObjectData())));

        DownloaderInputManifestDto manifest = new DownloaderInputManifestDto();
        downloaderWebClient.getRegServerAccessParamsDto().setUseSsl(false);
        downloaderWebClient.getBusinessObjectData(manifest);

        verify(mockHttpClientOperations).execute(any(), argThat(httpUriRequest -> httpUriRequest.getFirstHeader("Authorization") == null));
    }
    finally
    {
        ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", originalHttpClientOperations);
    }
}
 
Example #2
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 #3
Source File: StreamClientImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected HttpParams getRequestParams(StreamRequestMessage requestMessage) {
    HttpParams localParams = new BasicHttpParams();

    localParams.setParameter(
        CoreProtocolPNames.PROTOCOL_VERSION,
        requestMessage.getOperation().getHttpMinorVersion() == 0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1
    );

    // DefaultHttpClient adds HOST header automatically in its default processor

    // Add the default user agent if not already set on the message
    if (!requestMessage.getHeaders().containsKey(UpnpHeader.Type.USER_AGENT)) {
        HttpProtocolParams.setUserAgent(
            localParams,
            getConfiguration().getUserAgentValue(requestMessage.getUdaMajorVersion(), requestMessage.getUdaMinorVersion())
        );
    }

    return new DefaultedHttpParams(localParams, globalParams);
}
 
Example #4
Source File: RequestHandler.java    From djl-demo with Apache License 2.0 6 votes vote down vote up
/** Handles URLs predicted as malicious. */
private void blockedMaliciousSiteRequested() {
    try {
        HttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL");
        HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD);
        BufferedWriter bufferedWriter =
                new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        bufferedWriter.write(response.getStatusLine().toString());
        String headers =
                "Proxy-agent: FilterProxy/1.0\r\n"
                        + httpEntity.getContentType().toString()
                        + "\r\n"
                        + "Content-Length: "
                        + httpEntity.getContentLength()
                        + "\r\n\r\n";
        bufferedWriter.write(headers);
        // Pass index.html content
        bufferedWriter.write(EntityUtils.toString(httpEntity));
        bufferedWriter.flush();
        bufferedWriter.close();
    } catch (IOException e) {
        logger.error("Error writing to client when requested a blocked site", e);
    }
}
 
Example #5
Source File: WeixinUtil.java    From android-common-utils 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 #6
Source File: UnProtetcedMongoDBAccessTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception{
    mockStatic(HttpClientBuilder.class);
    mockStatic(HttpClient.class);
    mockStatic(CloseableHttpClient.class);
    mockStatic(HttpResponse.class);
    mockStatic(CloseableHttpResponse.class);
    
    closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
    HttpGet httpGet = PowerMockito.mock(HttpGet.class); 
    PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
    httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = PowerMockito.mock(HttpEntity.class);
    InputStream input = new ByteArrayInputStream("success".getBytes() );
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
    PowerMockito.when(entity.getContent()).thenReturn(input);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
 
Example #7
Source File: HTTPClientManager.java    From ForgePE with GNU Affero General Public License v3.0 6 votes vote down vote up
private HTTPClientManager() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    ConnManagerParams.setTimeout(params, 30000);
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    SSLSocketFactory sslSocketFactory;
    try {
        registry.register(new Scheme("https", NoCertSSLSocketFactory.createDefault(), 443));
    } catch (Exception e) {
        Log.e("MCPE_ssl", "Couldn\\'t create SSLSocketFactory");
    }

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, registry);
    this.mHTTPClient = new DefaultHttpClient(manager, params);
}
 
Example #8
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 #9
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 #10
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 #11
Source File: ElasticSearchInternalAccessRuleTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception{
    mockStatic(HttpClientBuilder.class);
    mockStatic(HttpClient.class);
    mockStatic(CloseableHttpClient.class);
    mockStatic(HttpResponse.class);
    mockStatic(CloseableHttpResponse.class);
    
    closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
    PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
    HttpGet httpGet = PowerMockito.mock(HttpGet.class); 
    PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
    httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = PowerMockito.mock(HttpEntity.class);
    InputStream input = new ByteArrayInputStream("lucene_version".getBytes() );
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
    PowerMockito.when(entity.getContent()).thenReturn(input);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
 
Example #12
Source File: OAuthRefreshTokenOnFailProcessorTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
private static OAuthRefreshTokenOnFailProcessor createProcessor(final String... grantJsons) throws IOException {
    final CloseableHttpClient client = mock(CloseableHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));

    final HttpEntity first = entity(grantJsons[0]);
    final HttpEntity[] rest = Arrays.stream(grantJsons).skip(1).map(OAuthRefreshTokenOnFailProcessorTest::entity)
        .toArray(HttpEntity[]::new);
    when(response.getEntity()).thenReturn(first, rest);

    when(client.execute(ArgumentMatchers.any(HttpUriRequest.class))).thenReturn(response);

    final Configuration configuration = configuration("403");

    final OAuthRefreshTokenOnFailProcessor processor = new OAuthRefreshTokenOnFailProcessor(OAuthState.createFrom(configuration), configuration) {
        @Override
        CloseableHttpClient createHttpClient() {
            return client;
        }
    };

    return processor;
}
 
Example #13
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example #14
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_non2xx_exception() throws IOException {
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");

    try {
        client.execute(
                new GenericApiGatewayRequestBuilder()
                        .withBody(new ByteArrayInputStream("test request".getBytes()))
                        .withHttpMethod(HttpMethodName.POST)
                        .withHeaders(headers)
                        .withResourcePath("/test/orders").build());

        Assert.fail("Expected exception");
    } catch (GenericApiGatewayException e) {
        assertEquals("Wrong status code", 404, e.getStatusCode());
        assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
    }
}
 
Example #15
Source File: MyHtttpClient.java    From Huochexing12306 with Apache License 2.0 6 votes vote down vote up
public synchronized static DefaultHttpClient getHttpClient() {
	try {
		HttpParams params = new BasicHttpParams();
		// 设置一些基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// 超时设置
		// 从连接池中取连接的超时时间
		ConnManagerParams.setTimeout(params, 10000); // 连接超时
		HttpConnectionParams.setConnectionTimeout(params, 10000); // 请求超时
		HttpConnectionParams.setSoTimeout(params, 30000);
		SchemeRegistry registry = new SchemeRegistry();
		Scheme sch1 = new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80);
		registry.register(sch1);
		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, registry);
		mHttpClient = new DefaultHttpClient(conMgr, params);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return mHttpClient;
}
 
Example #16
Source File: HttpEngine.java    From letv with Apache License 2.0 6 votes vote down vote up
private HttpParams createHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(3));
    ConnManagerParams.setMaxTotalConnections(params, 3);
    ConnManagerParams.setTimeout(params, 1000);
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    return params;
}
 
Example #17
Source File: AppletConfiguration.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads the configuration from the RuneScape website.
 */
public void load() throws IOException {
    parameters.clear();
    String text = normalize(Request.Get(CONFIG_URL)
            .version(HttpVersion.HTTP_1_1)
            .userAgent(USER_AGENT)
            .useExpectContinue()
            .execute()
            .returnContent().toString());
    String[] lines = text.split("\n");
    for (String line : lines) {
        extractKVPairInto(parameters, line);
    }

    String mainClass = parameters.get("initial_class");
    setMainClass(mainClass.replace(".class", ""));
    setDocumentBase(parameters.get("codebase"));
    setArchiveName(parameters.get("initial_jar"));
}
 
Example #18
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 #19
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 #20
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 #21
Source File: ZohoDocsUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java");
        HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0");
        httppost.setHeader("Cookie", cookies.toString());
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("multiupload_file", cbFile);
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into zoho docs...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {

            String tmp = EntityUtils.toString(resEntity);
//            System.out.println(tmp);
            if(tmp.contains("File Uploaded Successfully"))
                System.out.println("File Uploaded Successfully");

        }
        //    uploadresponse = response.getLastHeader("Location").getValue();
        //  System.out.println("Upload response : " + uploadresponse);
    }
 
Example #22
Source File: MySSLSocketFactory.java    From android-project-wo2b with Apache 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 #23
Source File: M3u8ContentParser.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
private DefaultHttpClient createHttpClient() {
	HttpParams params = new BasicHttpParams();
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
	HttpProtocolParams.setContentCharset(params,
			HTTP.DEFAULT_CONTENT_CHARSET);
	HttpProtocolParams.setUseExpectContinue(params, true);
	HttpConnectionParams.setConnectionTimeout(params,
			CONNETED_TIMEOUT * 1000);
	HttpConnectionParams.setSoTimeout(params, CONNETED_TIMEOUT * 1000);
	HttpConnectionParams.setSocketBufferSize(params, 8192);
	ConnManagerParams.setMaxTotalConnections(params, 4);
	SchemeRegistry schReg = new SchemeRegistry();
	schReg.register(new Scheme("http", PlainSocketFactory
			.getSocketFactory(), 80));
	schReg.register(new Scheme("https",
			SSLSocketFactory.getSocketFactory(), 443));

	ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
			params, schReg);

	return new DefaultHttpClient(connMgr, params);
}
 
Example #24
Source File: AweSomeApi.java    From javabase with Apache License 2.0 6 votes vote down vote up
private void post() throws IOException {
    //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优,
    //请求中包含String类型的请求体并将响应内容作为byte[]返回
    Request.Post("http://blog.csdn.net/vector_yi")
            .useExpectContinue()
            .version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
            .execute().returnContent().asBytes();


    //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体
    //将返回的响应内容存入文件
    Request.Post("http://blog.csdn.net/vector_yi")
            .addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
            .execute().saveContent(new File("result.dump"));

    Request.Post("http://targethost/login")
            .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
            .execute().returnContent();


}
 
Example #25
Source File: HttpDriverTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoPost404() throws IOException {
    CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = Mockito.mock(HttpEntity.class);

    String data = "Not Found";

    Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found" ));
    Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(entity);
    Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);

    HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
            .build();
    httpDriver.setHttpClient(httpClient);

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("data", "value"));

    String url = "https://localhost:4443/sample";

    String out = httpDriver.doPost(url, params);
    Assert.assertEquals(out, "");
}
 
Example #26
Source File: HttpDriverTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoPost201() throws IOException {
    CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = Mockito.mock(HttpEntity.class);

    String data = "Sample Server Response";

    Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "OK" ));
    Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(entity);
    Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);

    HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
            .build();
    httpDriver.setHttpClient(httpClient);

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("data", "value"));

    String url = "https://localhost:4443/sample";

    String out = httpDriver.doPost(url, params);
    Assert.assertEquals(out, data);
}
 
Example #27
Source File: HttpClientFactory.java    From miappstore with Apache License 2.0 6 votes vote down vote up
private static HttpParams createHttpParams() {
	final HttpParams params = new BasicHttpParams();
	// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
	// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
	HttpConnectionParams.setStaleCheckingEnabled(params, false);
	HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
	HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
	HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
	HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
	HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
	HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
	HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向

	ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
	ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
	ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
	return params;
}
 
Example #28
Source File: ConfigServerApiImplTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Before
public void initExecutor() throws IOException {
    CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
    when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
        HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
        mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append("  ");

        switch (mockReturnCode) {
            case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
            case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
        }

        BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
        BasicHttpEntity entity = new BasicHttpEntity();
        String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
        InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
        entity.setContent(stream);

        CloseableHttpResponse response = mock(CloseableHttpResponse.class);
        when(response.getEntity()).thenReturn(entity);
        when(response.getStatusLine()).thenReturn(statusLine);

        return response;
    });
    configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
 
Example #29
Source File: HttpDriverTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoGet() throws IOException {
    CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
    HttpEntity entity = Mockito.mock(HttpEntity.class);

    String data = "Sample Server Response";

    Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK" ));
    Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(entity);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);

    HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
            .build();

    httpDriver.setHttpClient(httpClient);

    String url = "https://localhost:4443/sample.html";

    String out = httpDriver.doGet(url);
    Assert.assertEquals(out, data);
}
 
Example #30
Source File: HttpClientFactory.java    From NetEasyNews with GNU General Public License v3.0 6 votes vote down vote up
private static HttpParams createHttpParams() {
	final HttpParams params = new BasicHttpParams();
	// 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。
	// 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间
	HttpConnectionParams.setStaleCheckingEnabled(params, false);
	HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间
	HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间
	HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小
	HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟)
	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本
	HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制
	HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码
	HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向

	ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时
	ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数
	ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数
	return params;
}