Java Code Examples for javax.net.ssl.HttpsURLConnection#setUseCaches()

The following examples show how to use javax.net.ssl.HttpsURLConnection#setUseCaches() . 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: UrlConnUtils.java    From webrtc_android with MIT License 6 votes vote down vote up
public static boolean download(String u, String path) {
    try {
        URL url = new URL(u);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        trustAllHosts(connection);
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        //可设置请求头
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setRequestProperty("Charset", "UTF-8");
        connection.connect();
        byte[] file = input2byte(connection.getInputStream());
        File file1 = writeBytesToFile(file, path);
        if (file1.exists()) {
            return true;
        }
    } catch (Exception e) {
        return false;
    }
    return false;
}
 
Example 2
Source File: GooglePhotosClient.java    From STGUploader with MIT License 6 votes vote down vote up
public void httpPhotoPost(File file) throws Exception {

        HttpsURLConnection connection = (HttpsURLConnection) new URL("https://photoslibrary.googleapis.com/v1/uploads").openConnection();
        connection.setUseCaches(false);
        connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
        connection.setRequestProperty("Connection", "close");
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setRequestProperty("Transfer-Encoding", "chunked");
        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestMethod("POST");
        connection.setRequestProperty("X-Goog-Upload-File-Name", file.getName());
        connection.setRequestProperty("X-Goog-Upload-Protocol", "raw");

        OutputStream output = connection.getOutputStream();
        writeFileToStream(file, output);
        output.flush();

        Logger.info("Response Code: " + connection.getResponseCode());
        String token = getResponseString(connection);
        Logger.info(token);
        createMediaItem(token);
    }
 
Example 3
Source File: LocationRetriever.java    From AppleWifiNlpBackend with Apache License 2.0 5 votes vote down vote up
private static void prepareConnection(HttpsURLConnection connection,
        int length) throws ProtocolException {
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty(HTTP_FIELD_CONTENT_TYPE, CONTENT_TYPE_URLENCODED);
    connection.setRequestProperty(HTTP_FIELD_CONTENT_LENGTH, String.valueOf(length));
}
 
Example 4
Source File: MultiPart.java    From constellation with Apache License 2.0 5 votes vote down vote up
/**
     * Post this multipart message using the given connection.
     *
     * @param conn An HTTPS connection.
     *
     * @return A (message, location) pair; the message is the http response
     * message, location is null if the response code was not in the 200 range.
     *
     * @throws IOException if the thread is interrupted during the connection.
     */
    public Pair<String, String> post(final HttpsURLConnection conn) throws IOException {
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", BrandingUtilities.APPLICATION_NAME);
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundary());
        conn.setRequestProperty("Content-Length", Integer.toString(size()));

        try (final OutputStream os = conn.getOutputStream()) {
            os.write(getBuffer());
        }

        final int code = conn.getResponseCode();

        final String location;
        final int responseClass = code / 100;
        if (responseClass == 2) {
            location = conn.getHeaderField("Location");
        } else {
            location = null;
        }

//        conn.getHeaderFields().entrySet().stream().forEach(entry ->
//        {
//            System.out.printf("@@MultiPart header %s: %s\n", entry.getKey(), entry.getValue());
//        });
//        System.out.printf("@@MultiPart response [%s]\n", new String(getBody(conn, code)));
        return new Pair<>(conn.getResponseMessage(), location);
    }
 
Example 5
Source File: HttpClient.java    From iyzipay-java with MIT License 5 votes vote down vote up
private String send(String url, HttpMethod httpMethod, InputStream content, Map<String, String> headers) {
    URLConnection raw;
    HttpsURLConnection conn = null;
    try {
        raw = new URL(url).openConnection();
        conn = HttpsURLConnection.class.cast(raw);

        conn.setSSLSocketFactory(socketFactory);
        conn.setRequestMethod(httpMethod.name());

        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(false);

        prepareHeaders(headers, conn);
        if (content != null) {
            prepareRequestBody(httpMethod, content, conn);
        }

        return new String(body(conn), Charset.forName("UTF-8"));
    } catch (Exception e) {
        throw new HttpClientException(e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 6
Source File: Utils.java    From NationStatesPlusPlus with MIT License 5 votes vote down vote up
private static String executeUploadToImgur(String url, String base64, String clientKey) throws IOException {
	HttpsURLConnection conn = (HttpsURLConnection) (new URL("https://api.imgur.com/3/image")).openConnection();
	conn.addRequestProperty("Authorization", "Client-ID " + clientKey);
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestMethod("POST");
	try (OutputStream out = conn.getOutputStream()) {
		if (url != null) {
			IOUtils.write("image=" + EncodingUtil.encodeURIComponent(url) + "&type=URL", out);
		} else {
			IOUtils.write("image=" + EncodingUtil.encodeURIComponent(base64) + "&type=base64", out);
		}
		out.flush();
	}

	try (InputStream stream = conn.getInputStream()) {
		Map<String, Object> result = new ObjectMapper().readValue(stream, new TypeReference<HashMap<String,Object>>() {});
		if (result != null && result.containsKey("data")) {
			@SuppressWarnings("unchecked")
			Map<String, Object> data = (Map<String, Object>) result.get("data");
			if (data != null && data.containsKey("link")) {
				String link = (String) data.get("link");
				return "https://" + link.substring(7);
			}
		}
	} finally {
		conn.disconnect();
	}
	return null;
}
 
Example 7
Source File: Engine.java    From acunetix-plugin with MIT License 5 votes vote down vote up
private Resp doDelete(String urlStr) throws IOException {
    HttpsURLConnection connection = openConnection(urlStr,"DELETE");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    Resp resp = new Resp();
    resp.respCode = connection.getResponseCode();
    return resp;
}
 
Example 8
Source File: Engine.java    From acunetix-plugin with MIT License 5 votes vote down vote up
private Resp doPost(String urlStr) throws IOException {
    HttpsURLConnection connection = openConnection(urlStr,"POST");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    Resp resp = new Resp();
    resp.respCode = connection.getResponseCode();
    return resp;
}
 
Example 9
Source File: GooglePhotosClient.java    From STGUploader with MIT License 5 votes vote down vote up
public void createMediaItem(String uploadToken) throws Exception{
    HttpsURLConnection connection = (HttpsURLConnection) new URL("https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate").openConnection();


    connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
    connection.setUseCaches(false);
    connection.setRequestProperty("Connection", "close");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true); // Triggers POST.

    String json = "{\n" +
            "  \"newMediaItems\": [\n" +
            "    {\n" +
            "      \"simpleMediaItem\": {\n" +
            "        \"uploadToken\": \""+uploadToken+"\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    OutputStream output = connection.getOutputStream();
    output.write(json.getBytes());
    output.flush();

    Logger.info("Response Code: " + connection.getResponseCode());
    Logger.info(getResponseString(connection));
}
 
Example 10
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the token url
 *
 * @param issuer from the idp-issuer-url
 * @param sslContext to support TLS with a self signed certificate in
 *     idp-certificate-authority-data
 * @return
 */
private String loadTokenURL(String issuer, SSLContext sslContext) {
  StringBuilder wellKnownUrl = new StringBuilder();
  wellKnownUrl.append(issuer);
  if (!issuer.endsWith("/")) {
    wellKnownUrl.append("/");
  }
  wellKnownUrl.append(".well-known/openid-configuration");

  try {
    URL wellKnown = new URL(wellKnownUrl.toString());
    HttpsURLConnection https = (HttpsURLConnection) wellKnown.openConnection();
    https.setRequestMethod("GET");
    if (sslContext != null) {
      https.setSSLSocketFactory(sslContext.getSocketFactory());
    }
    https.setUseCaches(false);
    int code = https.getResponseCode();

    if (code != HttpsURLConnection.HTTP_OK) {
      throw new RuntimeException(
          new StringBuilder()
              .append("Invalid response code for issuer - ")
              .append(code)
              .toString());
    }

    Scanner scanner = new Scanner(https.getInputStream(), StandardCharsets.UTF_8.name());
    String json = scanner.useDelimiter("\\A").next();

    JSONObject wellKnownJson = (JSONObject) new JSONParser().parse(json);
    String tokenUrl = (String) wellKnownJson.get("token_endpoint");

    return tokenUrl;

  } catch (IOException | ParseException e) {
    throw new RuntimeException("Could not refresh", e);
  }
}
 
Example 11
Source File: HttpsClientRequest.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
private static HttpsURLConnection getURLConnection(String requestUrl, String serverHome)
        throws IOException {
    setSSlSystemProperties(serverHome);
    URL url = new URL(requestUrl);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setReadTimeout(30000);
    conn.setConnectTimeout(15000);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    return conn;
}
 
Example 12
Source File: HttpUtil.java    From ssrpanel-v2ray with GNU General Public License v3.0 5 votes vote down vote up
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
    StringBuffer buffer = null;
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] tm = {new MyX509TrustManager()};
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(requestMethod);
        conn.setSSLSocketFactory(ssf);
        conn.connect();
        if (null != outputStr) {
            OutputStream os = conn.getOutputStream();
            os.write(outputStr.getBytes(StandardCharsets.UTF_8));
            os.close();
        }
        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        buffer = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer != null ? buffer.toString() : null;
}
 
Example 13
Source File: EventWriter.java    From android-perftracking with MIT License 4 votes vote down vote up
void begin() throws IOException {
  if (!config.enablePerfTrackingEvents) {
    return;
  }

  try {
    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    for (Map.Entry<String, String> entry : config.header.entrySet()) {
      connection.setRequestProperty(entry.getKey(), entry.getValue());
    }
    connection.setUseCaches(false);
    connection.setDoInput(false);
    connection.setDoOutput(true);
    connection.connect();

    writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
    writer.append("{\"app\":\"").append(config.app).append("\"")
        .append(",\"version\":\"").append(config.version).append("\"")
        .append(",\"relay_app_id\":\"").append(config.relayAppId).append("\"");

    if (envInfo.device != null) {
      writer.append(",\"device\":\"").append(envInfo.device).append("\"");
    }

    if (envInfo.getAppUsedMemory() > 0) {
      writer.append(",\"app_mem_used\":").append(Long.toString(envInfo.getAppUsedMemory()));
    }

    if (envInfo.getDeviceFreeMemory() > 0) {
      writer.append(",\"device_mem_free\":").append(Long.toString(envInfo.getDeviceFreeMemory()));
    }

    if (envInfo.getDeviceTotalMemory() > 0) {
      writer.append(",\"device_mem_total\":").append(Long.toString(envInfo.getDeviceTotalMemory()));
    }

    if (envInfo.getBatteryLevel() > 0) {
      writer.append(",\"battery_level\":").append(Float.toString(envInfo.getBatteryLevel()));
    }

    if (envInfo.getCountry() != null) {
      writer.append(",\"country\":\"").append(envInfo.getCountry()).append("\"");
    }

    if (envInfo.getRegion() != null) {
      writer.append(",\"region\":\"").append(envInfo.getRegion()).append("\"");
    }

    if (envInfo.network != null) {
      writer.append(",\"network\":\"").append(envInfo.network).append("\"");
    }

    if (envInfo.osName != null) {
      writer.append(",\"os\":\"").append(envInfo.osName).append("\"");
    }

    if (envInfo.osVersion != null) {
      writer.append(",\"os_version\":\"").append(envInfo.osVersion).append("\"");
    }

    writer.append(",\"measurements\":[");
    measurements = 0;

  } catch (Exception e) {
    if (config.debug) {
      Log.d(TAG, e.getMessage());
    }
    disconnect();
    if (e instanceof IOException) {
      throw e;
    }
  }
}
 
Example 14
Source File: CommonUtil.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
 * 发送https请求
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return 返回微信服务器响应的信息
 */
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		return buffer.toString();
	} catch (ConnectException ce) {
		log.error("连接超时:{}", ce);
	} catch (Exception e) {
		log.error("https请求异常:{}", e);
	}
	return null;
}
 
Example 15
Source File: HttpsTrustManager.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void downLoadFromUrlHttps(String urlStr, String fileName,
        String savePath) throws Exception {
    // 创建SSLContext
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManager[] tm = { new HttpsTrustManager() };
    // 初始化
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 获取SSLSocketFactory对象
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // url对象
    URL url = new URL(urlStr);
    // 打开连接
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    /**
     * 这一步的原因: 当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore
     * 但是服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。
     * 
     * 解决方法:让JRE相信所有的证书和对系统的域名和证书域名。
     * 
     * 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be <localhost>
     */
    conn.setHostnameVerifier(new HttpsTrustManager().new TrustAnyHostnameVerifier());
    // 设置一些参数
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    // 设置当前实例使用的SSLSoctetFactory
    conn.setSSLSocketFactory(ssf);
    conn.connect();
 
 
    // 得到输入流
    @Cleanup
    InputStream inputStream = conn.getInputStream();
    byte[] getData = readInputStream(inputStream);
    // 文件保存位置
    File saveDir = new File(savePath);
    if (!saveDir.exists()) {
        saveDir.mkdirs();
    }
    //输出流
    File file = new File(saveDir + File.separator + fileName);
    @Cleanup
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(getData);
}
 
Example 16
Source File: Client.java    From MaterialWeCenter with Apache License 2.0 4 votes vote down vote up
private String doPost(String apiUrl, Map<String, String> params) {
    Log.d("POST REQUEST", apiUrl);
    // 建立请求内容
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey())
                .append("=")
                .append(URLEncoder.encode(entry.getValue()))
                .append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // 发出请求
    try {
        URL url = new URL(apiUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // 附上Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // 发送请求内容
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // 接收返回信息
        int response = connection.getResponseCode();
        if (response == HttpsURLConnection.HTTP_OK) {
            // 保存Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // 处理返回的字符串流
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            String str = new String(byteArrayOutputStream.toByteArray());
            Log.d("POST RESPONSE", str);
            return str;
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}
 
Example 17
Source File: WxstoreUtils.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
public static JSONObject httpRequest(String requestUrl,
		String requestMethod, String outputStr) {
	logger.debug("*********HTTPREQUEST START********");
	logger.debug("*********requestUrl is "+
			requestUrl+" END AND requestMethod IS"
			+requestMethod + " END AND  outputStr" 
			+outputStr +" END ********");
	JSONObject jsonObject = null;
	StringBuffer buffer = new StringBuffer();
	try {
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new SecureRandom());

		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL url = new URL(requestUrl);
		HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
				.openConnection();
		httpUrlConn.setSSLSocketFactory(ssf);

		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);

		httpUrlConn.setRequestMethod(requestMethod);

		if ("GET".equalsIgnoreCase(requestMethod)) {
			httpUrlConn.connect();
		}

		if (null != outputStr) {
			OutputStream outputStream = httpUrlConn.getOutputStream();

			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}

		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(
				inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(
				inputStreamReader);

		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();

		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		jsonObject = JSONObject.fromObject(buffer.toString());
		if (jsonObject.containsKey("errcode") && jsonObject.getInt("errcode") != 0) {
			logger.debug("********* ERROR********{}",buffer.toString());
			logger.debug("*********HTTPREQUEST END********");
			throw new WexinReqException("httpRequest Method!errcode="
					+ jsonObject.getString("errcode") + ",errmsg = "
					+ jsonObject.getString("errmsg"));
		} else {
			logger.debug("********* SUCCESS END********");
		}
	} catch (ConnectException ce) {
		System.out.println("Weixin server connection timed out.");
	} catch (Exception e) {
		System.out.println("https request error:{}" + e.getMessage());
	}
	return jsonObject;
}
 
Example 18
Source File: SfmtaApiCaller.java    From core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
	try {
		// Create the connection
		URL url = new URL(baseUrl);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

		// Set parameters for the connection
		con.setRequestMethod("POST"); 
		con.setRequestProperty("content-type", "application/json");
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches (false);
		
		// API now uses basic authentication
		String authString = login.getValue() + ":" + password.getValue();
		byte[] authEncBytes =
				Base64.encodeBase64(authString.getBytes());
		String authStringEnc = new String(authEncBytes);
		con.setRequestProperty("Authorization", "Basic "
				+ authStringEnc);

		// Set the timeout so don't wait forever (unless timeout is set to 0)
		int timeoutMsec = timeout.getValue();
		con.setConnectTimeout(timeoutMsec);
		con.setReadTimeout(timeoutMsec);

		// Write the json data to the connection
		DataOutputStream wr = new DataOutputStream(con.getOutputStream ());
		wr.writeBytes(jsonStr);
		wr.flush();
		wr.close();
		
		// Get the response
		int responseCode = con.getResponseCode();
		
		// If wasn't successful then log the response so can debug
		if (responseCode != 200) {			
			String responseStr = "";
			if (responseCode != 500) {
				// Response code indicates there was a problem so get the
				// reply in case API returned useful error message
				InputStream inputStream = con.getErrorStream();
				if (inputStream != null) {
					BufferedReader in =
							new BufferedReader(new InputStreamReader(
									inputStream));
					String inputLine;
					StringBuffer response = new StringBuffer();
					while ((inputLine = in.readLine()) != null) {
						response.append(inputLine);
					}
					in.close();
					responseStr = response.toString();
				}
			}

			// Lot that response code indicates there was a problem
			logger.error("Bad HTTP response {} when writing data to SFMTA "
					+ "API. Response text=\"{}\" URL={} json=\n{}",
					responseCode, responseStr, baseUrl, jsonStr);
		}

		// Done so disconnect just for the heck of it
		con.disconnect();
		
		// Return whether was successful
		return responseCode == 200;
	} catch (IOException e) {
		logger.error("Exception when writing data to SFMTA API: \"{}\" "
				+ "URL={} json=\n{}", 
				e.getMessage(), baseUrl, jsonStr);
		
		// Return that was unsuccessful
		return false;
	}
	
}
 
Example 19
Source File: WeixinUtil.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 发起https请求并获取结果
 * 
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
 */
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                    httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                    OutputStream outputStream = httpUrlConn.getOutputStream();
                    // 注意编码格式,防止中文乱码
                    outputStream.write(outputStr.getBytes("UTF-8"));
                    outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
            //jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
    	org.jeecgframework.core.util.LogUtil.info("Weixin server connection timed out.");
    } catch (Exception e) {
    	org.jeecgframework.core.util.LogUtil.info("https request error:{}"+e.getMessage());
    }
    return jsonObject;
}
 
Example 20
Source File: CompileRevenjNet.java    From dsl-compiler-client with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static boolean downloadFromGithub(
		final Context context,
		final String name,
		final String zip,
		final String additionalZip,
		final File target) throws ExitException {
	if (!context.contains(Download.INSTANCE)) {
		if (!context.canInteract()) {
			context.error("Download option not enabled.\n" +
					"Enable download option, change dependencies path or place " + name + " files in specified folder: " + target.getAbsolutePath());
			throw new ExitException();
		}
		final String answer = context.ask("Do you wish to download latest " + name + " version from the Internet (y/N):");
		if (!"y".equalsIgnoreCase(answer)) {
			throw new ExitException();
		}
	}
	try {
		context.show("Downloading " + name + " from GitHub...");
		final URL latest = new URL("https://github.com/ngs-doo/revenj/releases/latest");
		final HttpsURLConnection conn = (HttpsURLConnection) latest.openConnection();
		conn.setInstanceFollowRedirects(false);
		conn.setUseCaches(false);
		conn.connect();
		final String tag;
		if (conn.getResponseCode() != 302) {
			context.warning("Error downloading " + name + " from GitHub. Will continue with tag 1.5.0. Expecting redirect. Got: " + conn.getResponseCode());
			tag = "1.5.0";
		} else {
			final String redirect = conn.getHeaderField("Location");
			tag = redirect.substring(redirect.lastIndexOf('/') + 1);
		}
		final URL coreUrl = new URL("https://github.com/ngs-doo/revenj/releases/download/" + tag + "/" + zip + ".zip");
		Utils.unpackZip(context, target, coreUrl);
		if (additionalZip != null) {
			final URL zipUrl = new URL("https://github.com/ngs-doo/revenj/releases/download/" + tag + "/" + additionalZip + ".zip");
			Utils.unpackZip(context, target, zipUrl);
		}
	} catch (IOException ex) {
		context.error("Unable to download " + name + " from GitHub.");
		context.error(ex);
		return false;
	}
	return true;
}