项目:Clases-2017c1
文件:UrlRequest.java
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
int responseCode = connection.getResponseCode();
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.read(buffer)) > 0) {
responseBody.write(buffer,bytesRead);
}
listener.onReceivedBody(responseCode,responseBody.toByteArray());
}
catch (Exception e) {
listener.onError(e);
}
}
项目:android-dev-challenge
文件:NetworkUtils.java
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
项目:azure-spring-boot
文件:AzureADGraphClient.java
public static String getUserMembershipsV1(String accesstoken) throws Exception {
final String userMembershipRestAPIv1 = "https://graph.windows.net/me/memberOf?api-version=1.6";
final URL url = new URL(userMembershipRestAPIv1);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
conn.setRequestProperty("api-version","1.6");
conn.setRequestProperty("Authorization",accesstoken);
conn.setRequestProperty("Accept","application/json;odata=minimalMetadata");
final String responseInjson = getResponseStringFromConn(conn);
final int responseCode = conn.getResponseCode();
if (responseCode == HTTPResponse.SC_OK) {
return responseInjson;
} else {
throw new Exception(responseInjson);
}
}
项目:awe-awesomesky
文件:HttpUtil.java
public void doGet(String url) throws Exception{
URL localURL = new URL(url);
URLConnection con = openConnection(localURL);
HttpURLConnection httpCon = (HttpURLConnection)con;
httpCon.setRequestProperty("Accept-Charset",CHARSET);
httpCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
if(httpCon.getResponseCode()>=300){
throw new RuntimeException("请求失败...");
}
InputStreamReader isr = new InputStreamReader(httpCon.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String res = reader.readLine();
System.out.println(res);
isr.close();
reader.close();
}
/**
* A client for <a href="https://haveibeenpwned.com/">Have I Been Pwned</a>'s online password
* checking. Passwords are hashed with SHA-1 before being sent.
*
* @return an online database of breached passwords
*/
static BreachDatabase haveIBeenPwned() {
return password -> {
try {
final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
final byte[] hash = sha1.digest(PasswordPolicy.normalize(password));
final StringBuilder s =
new StringBuilder("https://haveibeenpwned.com/api/v2/pwnedpassword/");
for (byte b : hash) {
s.append(String.format("%02x",b));
}
final HttpURLConnection conn = (HttpURLConnection) new URL(s.toString()).openConnection();
return conn.getResponseCode() == 200;
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
};
}
项目:AndroidbackendlessChat
文件:Response.java
static List<Response> createResponsesFromString(String responseString,HttpURLConnection connection,RequestBatch requests,boolean isFromCache) throws FacebookException,JSONException,IOException {
JSONTokener tokener = new JSONTokener(responseString);
Object resultObject = tokener.nextValue();
List<Response> responses = createResponsesFromObject(connection,requests,resultObject,isFromCache);
Logger.log(LoggingBehavior.REQUESTS,RESPONSE_LOG_TAG,"Response\n Id: %s\n Size: %d\n Responses:\n%s\n",requests.getId(),responseString.length(),responses);
return responses;
}
项目:GitHub
文件:CacheTest.java
@Test public void networkInterceptorInvokedForConditionalGet() throws Exception {
server.enqueue(new MockResponse()
.addHeader("ETag: v1")
.setBody("A"));
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
// Seed the cache.
HttpUrl url = server.url("/");
assertEquals("A",get(url).body().string());
final atomicreference<String> ifNoneMatch = new atomicreference<>();
client = client.newBuilder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
ifNoneMatch.compareAndSet(null,chain.request().header("if-none-match"));
return chain.proceed(chain.request());
}
}).build();
// Confirm the value is cached and intercepted.
assertEquals("A",get(url).body().string());
assertEquals("v1",ifNoneMatch.get());
}
@RunAsClient
@Test(groups = TEST_GROUP_JWT,description = "Verify that the token issuer claim is as expected")
public void verifyIssuerClaim() throws Exception {
Reporter.log("Begin verifyIssuerClaim");
String uri = baseURL.toExternalForm() + "/endp/verifyIssuer";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.iss.name(),TEST_ISSUER)
.queryParam(Claims.auth_time.name(),authTimeClaim);
Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION,"Bearer " + token).get();
Assert.assertEquals(response.getStatus(),HttpURLConnection.HTTP_OK);
String replyString = response.readEntity(String.class);
JsonReader jsonReader = Json.createReader(new StringReader(replyString));
JsonObject reply = jsonReader.readobject();
Reporter.log(reply.toString());
Assert.assertTrue(reply.getBoolean("pass"),reply.getString("msg"));
}
项目:microprofile-jwt-auth
文件:ProviderInjectionTest.java
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,description = "Verify that the injected jti claim is as expected")
public void verifyInjectedJTI2() throws Exception {
Reporter.log("Begin verifyInjectedJTI\n");
String uri = baseURL.toExternalForm() + "/endp/verifyInjectedJTI";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.jti.name(),"a-123")
.queryParam(Claims.auth_time.name(),reply.getString("msg"));
}
/**
* Sends out the WSDL (and other referenced documents)
* in response to the GET requests to URLs like "?wsdl" or "?xsd=2".
*
* @param con
* The connection to which the data will be sent.
*
* @throws java.io.IOException when I/O errors happen
*/
public void publishWSDL(@NotNull WShttpconnection con) throws IOException {
con.getinput().close();
SDDocument doc = wsdls.get(con.getQueryString());
if (doc == null) {
writeNotFoundErrorPage(con,"Invalid Request");
return;
}
con.setStatus(HttpURLConnection.HTTP_OK);
con.setContentTypeResponseHeader("text/xml;charset=utf-8");
OutputStream os = con.getProtocol().contains("1.1") ? con.getoutput() : new Http10OutputStream(con);
PortAddressResolver portAddressResolver = getPortAddressResolver(con.getBaseAddress());
DocumentAddressResolver resolver = getDocumentAddressResolver(portAddressResolver);
doc.writeto(portAddressResolver,resolver,os);
os.close();
}
项目:util4j
文件:HttpUtil.java
public HttpURLConnection buildSSLConn(String url)throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null,new TrustManager[]{new TrustAnyTrustManager()},new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setConnectTimeout(connectTimeOut);
conn.setReadTimeout(readTimeOut);
return conn;
}
项目:pay
文件:WebUtils.java
protected static String getResponseAsstring(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsstring(conn.getInputStream(),charset);
} else {
String msg = getStreamAsstring(es,charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
项目:android-dev-challenge
文件:NetworkUtils.java
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response,null if no response
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
项目:athena
文件:VirtualNetworkWebResourceTest.java
/**
* Tests adding of new virtual network using POST via JSON stream.
*/
@Test
public void testPostVirtualNetwork() {
expect(mockVnetAdminService.createVirtualNetwork(tenantId2)).andReturn(vnet1);
expectLastCall();
replay(mockVnetAdminService);
WebTarget wt = target();
InputStream jsonStream = TenantWebResourceTest.class
.getResourceAsstream("post-tenant.json");
Response response = wt.path("vnets").request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(jsonStream));
assertthat(response.getStatus(),is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertthat(location,Matchers.startsWith("/vnets/" + vnet1.id().toString()));
verify(mockVnetAdminService);
}
项目:SkillWill
文件:SessionService.java
private boolean isTokenInProxy(String token) {
try {
URL authUrl = new URL(oAuthUrl);
HttpURLConnection connection = (HttpURLConnection) authUrl.openConnection();
connection.addRequestProperty("Cookie","_oauth2_proxy=" + token);
connection.connect();
int resonseCode = connection.getResponseCode();
connection.disconnect();
logger.debug("Successfully checked token with oauth proxy,result {}",resonseCode);
return resonseCode == HttpStatus.ACCEPTED.value();
} catch (IOException e) {
logger.error("Failed to check session token at oauth Proxy");
return false;
}
}
项目:belling-spring-rabbitmq
文件:HttpRequester.java
/**
* 得到响应对象
*
* @param urlConnection
* @return 响应对象
* @throws IOException
*/
private HttpRespons makeContent(String urlString,HttpURLConnection urlConnection) throws IOException {
HttpRespons httpResponser = new HttpRespons();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,Charset.forName(this.defaultContentEncoding)));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding;
httpResponser.urlString = urlString;
httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();
httpResponser.content = temp.toString();
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
return httpResponser;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
项目:Android-Programming-BigNerd
文件:FlickrFetchr.java
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() + ": with " +
urlSpec);
}
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer,bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
@Override
public Health health() {
try {
URL url =
new URL("http://greglturnquist.com/learning-spring-boot");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
int statusCode = conn.getResponseCode();
if (statusCode >= 200 && statusCode < 300) {
return Health.up().build();
} else {
return Health.down()
.withDetail("HTTP Status Code",statusCode)
.build();
}
} catch (IOException e) {
return Health.down(e).build();
}
}
@Nullable
public static String getResponseFromHttpUrl(URL url,Context context) throws IOException {
if (updateConnectionState(context)) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} catch (Exception e) {
e.printstacktrace();
return null;
} finally {
urlConnection.disconnect();
}
} else {
return null;
}
}
项目:shabdiz
文件:URLUtils.java
/**
* Pings a given {@code url} for availability. Effectively sends a HEAD request and returns {@code true} if the response code is in
* the {@code 200} - {@code 399} range.
* @param url the url to be pinged.
* @param timeout_millis the timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return {@code true} if the given {@code url} has returned response code within the range of {@code 200} - {@code 399} on a HEAD request,{@code false} otherwise
*/
public static boolean ping(final URL url,final int timeout_millis) {
try {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(timeout_millis);
connection.setReadTimeout(timeout_millis);
connection.setRequestMethod(HEAD_REQUEST_METHOD);
final int response_code = connection.getResponseCode();
return HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_BAD_REQUEST;
}
catch (IOException exception) {
return false;
}
}
static String getRedirectURL(String url) {
String redirectUrl = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// do not automatically follow the redirection
// otherwise we get too many redirections exception
conn.setInstanceFollowRedirects(false);
if(conn.getResponseCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT)
redirectUrl = conn.getHeaderField("Location");
} catch (Exception e) {
// throw new RuntimeException(e);
}
return redirectUrl;
}
项目:productai-java-sdk
文件:RequestHelper.java
public static <T extends BaseResponse> HttpResponse getResponse(BaseRequest<T> request) throws Exception {
HttpResponse httpResponse;
HttpURLConnection connection = createRequest(request);
if (request.getRequestMethod() != HttpMethod.GET) {
if (request.getQueryBytes() != null) {
writeRequestParas(connection,request.getQueryBytes());
} else {
writeRequestParas(connection,request.getQueryString());
}
}
int statusCode = connection.getResponseCode();
byte[] bytes = readStreamBytes(connection);
httpResponse = new HttpResponse();
httpResponse.setStatusCode(statusCode);
httpResponse.setResponseBytes(bytes);
httpResponse.setHeaders(connection.getHeaderFields());
return httpResponse;
}
项目:pre-dem-android
文件:HttpMonitorManager.java
private boolean sendRequest(String url,String content) {
LogUtils.d(TAG,"------url = " + url + "\ncontent = " + content);
try {
HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
.setRequestMethod("POST")
.setHeader("Content-Type","application/x-gzip")
.setHeader("content-encoding","gzip")
.setRequestBody(content)
.setGzip(true)
.build();
int responseCode = httpConn.getResponseCode();
boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
return successful;
} catch (Exception e) {
e.printstacktrace();
return false;
}
}
项目:microprofile-jwt-auth
文件:PrimitiveInjectionTest.java
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,description = "Verify that the injected groups claim is as expected")
public void verifyInjectedGroups() throws Exception {
Reporter.log("Begin verifyInjectedGroups\n");
String uri = baseURL.toExternalForm() + "/endp/verifyInjectedGroups";
WebTarget echoEndpointTarget = ClientBuilder.newClient()
.target(uri)
.queryParam(Claims.groups.name(),new String[]{
"Echoer","Tester","group1","group2"})
.queryParam(Claims.auth_time.name(),reply.getString("msg"));
}
项目:Transwarp-Sample-Code
文件:KerberosWebHDFSConnection.java
/**
* <b>LISTSTATUS</b>
*
* curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS"
*
* @param path
* @return
* @throws MalformedURLException
* @throws IOException
* @throws AuthenticationException
*/
public String listStatus(String path) throws MalformedURLException,IOException,AuthenticationException {
ensureValidToken();
System.out.println("Token = "+token.isSet());
HttpURLConnection conn = authenticatedURL.openConnection(
new URL(new URL(httpfsUrl),messageformat.format(
"/webhdfs/v1/{0}?delegation="+delegation+"&op=LISTSTATUS",URLUtil.encodePath(path))),token);
conn.setRequestMethod("GET");
conn.connect();
String resp = result(conn,true);
conn.disconnect();
return resp;
}
项目:GitTalent
文件:CouchbaseContainer.java
public void callCouchbaseRestAPI(String url,String payload) throws IOException {
String fullUrl = urlBase + url;
HttpURLConnection httpconnection = (HttpURLConnection) ((new URL(fullUrl).openConnection()));
httpconnection.setDoOutput(true);
httpconnection.setRequestMethod("POST");
httpconnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
String encoded = Base64.encode((clusterUsername + ":" + clusterPassword).getBytes("UTF-8"));
httpconnection.setRequestProperty("Authorization","Basic " + encoded);
DataOutputStream out = new DataOutputStream(httpconnection.getoutputStream());
out.writeBytes(payload);
out.flush();
out.close();
httpconnection.getResponseCode();
httpconnection.disconnect();
}
@SmallTest
@Feature({"cronet"})
@CompareDefaultWithcronet
public void testPostWithoutContentLengthOneMassiveWrite() throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getoutputStream();
byte[] largeData = TestUtil.getLargeData();
out.write(largeData);
assertEquals(200,connection.getResponseCode());
assertEquals("OK",connection.getResponseMessage());
TestUtil.checkLargeData(TestUtil.getResponseAsstring(connection));
connection.disconnect();
}
项目:cat-is-a-dog
文件:DownloadImageTask.java
/**
* Download the image from the given URL
* @param urlString the URL to download
* @return a bitmap of the downloaded image
*/
private Bitmap downloadImage(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (bmp != null) {
return bmp;
}
}
catch (Exception e) {
e.printstacktrace();
}
return bmp;
}
项目:woodpecker
文件:GetRequest.java
public String performRequest(HttpURLConnection httpconnection) {
try {
httpconnection.setRequestMethod("GET");
addHeaders(httpconnection);
String response = readInputSteam(httpconnection.getInputStream());
httpconnection.getInputStream().close();
peck.getResponse().setRawResponse(response);
peck.getResponse().setResponseCode(httpconnection.getResponseCode());
peck.getResponse().setHeaders(httpconnection.getHeaderFields());
return response;
} catch (IOException e) {
generateErrorResponse(peck.getResponse(),httpconnection);
return null;
} finally {
httpconnection.disconnect();
}
}
@Test
public void testDemoResponseError503() {
reset(mainSceneMock);
MainPresenterImpl presenter = new MainPresenterImpl(schedulersProvider,pokeDataSource);
MockResponse response = new MockResponse();
response.setResponseCode(HttpURLConnection.HTTP_UNAVAILABLE);
getErrorMockWebServer().enqueue(response);
presenter.onSceneAdded(mainSceneMock,null);
testScheduler.triggerActions();
verify(mainSceneMock,times(0)).setApiText(anyString());
verify(mainSceneMock,times(1)).showErrorDialog("Fire on the Server");
}
项目:GitHub
文件:responsecacheTest.java
@Test public void varyMultipleFieldValuesWithmatch() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Cache-Control: max-age=60")
.addHeader("vary: Accept-Language")
.setBody("A"));
server.enqueue(new MockResponse()
.setBody("B"));
URL url = server.url("/").url();
HttpURLConnection multiConnection1 = openConnection(url);
multiConnection1.setRequestProperty("Accept-Language","fr-CA,fr-FR");
multiConnection1.addRequestProperty("Accept-Language","en-US");
assertEquals("A",readAscii(multiConnection1));
HttpURLConnection multiConnection2 = openConnection(url);
multiConnection2.setRequestProperty("Accept-Language",fr-FR");
multiConnection2.addRequestProperty("Accept-Language",readAscii(multiConnection2));
}
private Bitmap downloadUrl(String myurl) throws IOException {
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
return null;
}
}
/**
* Set replication for an existing file.
*
* @param src file name
* @param replication new replication
*
* @return true if successful;
* false if file does not exist or is a directory
*
* @throws IOException
*/
@Override
public boolean setReplication(Path src,short replication)
throws IOException {
Map<String,String> params = new HashMap<String,String>();
params.put(OP_ParaM,Operation.SETREPLICATION.toString());
params.put(REPLICATION_ParaM,Short.toString(replication));
HttpURLConnection conn =
getConnection(Operation.SETREPLICATION.getmethod(),params,src,true);
HttpExceptionUtils.validateResponse(conn,HttpURLConnection.HTTP_OK);
JSONObject json = (JSONObject) Httpfsutils.jsonParse(conn);
return (Boolean) json.get(SET_REPLICATION_JSON);
}
项目:bubichain-sdk-java
文件:HttpKit.java
/**
* 鍙戦�丳ost璇锋眰
* @param url 璇锋眰鍦板潃
* @param params 璇锋眰鍙傛暟
* @param https 鏄惁鍚姩https
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url,String params) throws IOException,NoSuchAlgorithmException,NoSuchProviderException,KeyManagementException {
if(enableSSL){
return post(url,true);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(50000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(50000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getoutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
}
项目:GitHub
文件:JavaApiConverter.java
/**
* Creates an OkHttp {@link Response} using the supplied {@link URI} and {@link URLConnection} to
* supply the data. The URLConnection is assumed to already be connected. If this method returns
* {@code null} the response is uncacheable.
*/
public static Response createOkResponseForCachePut(URI uri,URLConnection urlConnection)
throws IOException {
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
Response.Builder okResponseBuilder = new Response.Builder();
// Request: Create one from the URL connection.
Headers responseHeaders = createHeaders(urlConnection.getHeaderFields());
// Some request headers are needed for vary caching.
Headers varyHeaders = varyHeaders(urlConnection,responseHeaders);
if (varyHeaders == null) {
return null;
}
// OkHttp's Call API requires a placeholder body; the real body will be streamed separately.
String requestMethod = httpUrlConnection.getRequestMethod();
RequestBody placeholderBody = HttpMethod.requiresRequestBody(requestMethod)
? Util.EMPTY_REQUEST
: null;
Request okRequest = new Request.Builder()
.url(uri.toString())
.method(requestMethod,placeholderBody)
.headers(varyHeaders)
.build();
okResponseBuilder.request(okRequest);
// Status line
StatusLine statusLine = StatusLine.parse(extractStatusLine(httpUrlConnection));
okResponseBuilder.protocol(statusLine.protocol);
okResponseBuilder.code(statusLine.code);
okResponseBuilder.message(statusLine.message);
// A network response is required for the Cache to find any vary headers it needs.
Response networkResponse = okResponseBuilder.build();
okResponseBuilder.networkResponse(networkResponse);
// Response headers
Headers okHeaders = extractOkResponseHeaders(httpUrlConnection,okResponseBuilder);
okResponseBuilder.headers(okHeaders);
// Response body
ResponseBody okBody = createOkBody(urlConnection);
okResponseBuilder.body(okBody);
// Handle SSL handshake @R_577_4045@ion as needed.
if (httpUrlConnection instanceof HttpsURLConnection) {
HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) httpUrlConnection;
Certificate[] peerCertificates;
try {
peerCertificates = httpsUrlConnection.getServerCertificates();
} catch (SSLPeerUnverifiedException e) {
peerCertificates = null;
}
Certificate[] localCertificates = httpsUrlConnection.getLocalCertificates();
String cipherSuiteString = httpsUrlConnection.getCipherSuite();
CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
Handshake handshake = Handshake.get(Tlsversion.SSL_3_0,cipherSuite,nullSafeImmutableList(peerCertificates),nullSafeImmutableList(localCertificates));
okResponseBuilder.handshake(handshake);
}
return okResponseBuilder.build();
}
项目:uniquid-utils
文件:RegistryDAOImpl.java
@Override
public String retrieveProviderName(final String providerAddress) throws RegistryException {
try {
URL url = new URL(GET_URL.replace("%1&s",registryAddress));
return HttpUtils.retrieveDataViaHttpGet(url,new ResponseDecoder<String>() {
@Override
public int getExpectedResponseCode() {
return HttpURLConnection.HTTP_OK;
}
@Override
public String manageResponse(String serverResponse) throws Exception {
return addressFromJsonString(serverResponse,providerAddress);
}
@Override
public String manageUnexpectedResponseCode(int responseCode,String responseMessage) throws Exception {
if (HttpURLConnection.HTTP_NOT_FOUND == responseCode)
return null;
throw new RegistryException("Server returned " + responseCode + " " + responseMessage);
}
});
} catch (Throwable t) {
throw new RegistryException("Unexpected Exception",t);
}
}
public static void downloadFile(String sourceURL,String fileNameWithPath) throws IOException{
final int BUFFER_SIZE = 4096;
URL url = new URL(sourceURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("file=");
if (index > 0)
fileName = disposition.substring(index + 10,disposition.length() - 1);
} else {
fileName = sourceURL.substring(sourceURL.lastIndexOf("/") + 1,sourceURL.length());
}
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileNameWithPath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer,bytesRead);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
}
/**
* Checks if a URL exists and can respond to an HTTP request.
* @param url The URL to check.
* @return True if the URL exists,false if it doesn't or an error occured.
*/
public static boolean checkURL(String url) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
return false;
}
}
项目:rapidminer
文件:MarketplaceUpdateManager.java
private InputStream openStream(URL url,ProgressListener listener,int minProgress,int maxProgress) throws IOException {
HttpURLConnection con = (HttpURLConnection)url.openConnection();
WebServicetools.setURLConnectionDefaults(con);
con.setDoInput(true);
con.setDoOutput(false);
String lengthStr = con.getHeaderField("Content-Length");
InputStream urlIn;
try {
urlIn = con.getInputStream();
} catch (IOException var11) {
throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(),var11);
}
if(lengthStr != null && !lengthStr.isEmpty()) {
try {
long e = Long.parseLong(lengthStr);
return new ProgressReportingInputStream(urlIn,listener,minProgress,maxProgress,e);
} catch (NumberFormatException var10) {
LogService.getRoot().log(Level.WARNING,I18N.getMessage(LogService.getRoot().getResourceBundle(),"com.rapid_i.deployment.update.client.UpdateManager.sending_illegal_content_length_error",new Object[]{lengthStr}),var10);
return urlIn;
}
} else {
LogService.getRoot().log(Level.WARNING,"com.rapid_i.deployment.update.client.UpdateManager.sending_content_length_error");
return urlIn;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。