Java Code Examples for javax.net.ssl.HttpsURLConnection#setDoInput()
The following examples show how to use
javax.net.ssl.HttpsURLConnection#setDoInput() .
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: PxgridControl.java From pxgrid-rest-ws with Apache License 2.0 | 6 votes |
private HttpsURLConnection getHttpsURLConnection(String urlSuffix) throws IOException { String url = "https://" + config.getHostnames()[0] + ":8910/pxgrid/control/" + urlSuffix; URL conn = new URL(url); HttpsURLConnection https = (HttpsURLConnection) conn.openConnection(); // SSL and Auth https.setSSLSocketFactory(config.getSSLContext().getSocketFactory()); https.setRequestMethod("POST"); String userPassword = config.getNodeName() + ":" + config.getPassword(); String encoded = Base64.getEncoder().encodeToString(userPassword.getBytes()); https.setRequestProperty("Authorization", "Basic " + encoded); https.setDoInput(true); https.setDoOutput(true); return https; }
Example 2
Source File: MailSenderUtil.java From kardio with Apache License 2.0 | 5 votes |
/** * Sends the slack Alert. * * @param hVo * @param slackURL * @throws IOException */ private static void sendSlackAlertByWebHook(HealthCheckVO hVo, String slackURL, String subject) throws IOException { String slackMessage = "{\"username\": \"CCP Service Health Dashboard\", \"text\": \"" + subject + ".\n" + "Current Status : " + hVo.getStatus().getStatus().getStatusDesc() + "\nMessage : " + (hVo.getFailureStatusMessage() == null ? "" : hVo.getFailureStatusMessage().replace('\"', '\'')) + "\n\", \"icon_emoji\": \":satellite_antenna:\"}"; logger.debug("Slack Message : " + slackMessage); URL myurl = new URL(slackURL); HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-length", String.valueOf(slackMessage.length())); con.setRequestProperty("Content-Type","application/json"); con.setDoOutput(true); con.setDoInput(true); DataOutputStream output = new DataOutputStream(con.getOutputStream()); output.writeBytes(slackMessage); output.flush(); output.close(); logger.debug("Message pushed to slack channnel : " + slackURL); logger.debug("Resp Code:" + con.getResponseCode()); logger.debug("Resp Message:" + con.getResponseMessage()); }
Example 3
Source File: Uploader.java From cs-actions with Apache License 2.0 | 5 votes |
private static HttpsURLConnection getBasicHTTPSConnection(final URL url) throws IOException { final HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(hv); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(false); return conn; }
Example 4
Source File: HttpUtils.java From mclauncher-api with MIT License | 5 votes |
/** * Execute a secured POST request * @param url URL to request * @param keyInput the secret key to be used * @param parameters Parameters in form <code>name=Tom&password=pass123</code>. They needn't to be URL-encoded(it will be done automatically) * @return The result of request * @throws Exception I/O Exception, HTTP errors or invalid key */ public static String securePostWithKey(String url, InputStream keyInput, String parameters) throws Exception { URL u = new URL(url); HttpsURLConnection connection = (HttpsURLConnection) u.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + parameters.getBytes().length); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); Certificate cert = connection.getServerCertificates()[0]; byte[] serverKey = cert.getPublicKey().getEncoded(); DataInputStream dis = new DataInputStream(keyInput); for (int i = 0; i < serverKey.length; ++i) { if (dis.readByte() != serverKey[i]) { throw new SecurityException("Invalid Server Key!"); } } DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.writeBytes(URLEncoder.encode(parameters, "utf-8")); dos.flush(); dos.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = br.readLine()) != null) { response = response.append(line).append('\r'); } br.close(); connection.disconnect(); return response.toString(); }
Example 5
Source File: SendRefreshTokenAsyncTask.java From OneNoteAPISampleAndroid with Apache License 2.0 | 5 votes |
private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception { /** * A new connection to the endpoint that processes requests for refreshing the access token */ HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL)).openConnection(); refreshTokenConnection.setDoOutput(true); refreshTokenConnection.setRequestMethod("POST"); refreshTokenConnection.setDoInput(true); refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE); refreshTokenConnection.connect(); OutputStream refreshTokenRequestStream = null; try { refreshTokenRequestStream = refreshTokenConnection.getOutputStream(); String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID, TOKEN_REFRESH_REDIRECT_URL, refreshToken); refreshTokenRequestStream.write(requestBody.getBytes()); refreshTokenRequestStream.flush(); } finally { if(refreshTokenRequestStream != null) { refreshTokenRequestStream.close(); } } if(refreshTokenConnection.getResponseCode() == 200) { return parseRefreshTokenResponse(refreshTokenConnection); } else { throw new Exception("The attempt to refresh the access token failed"); } }
Example 6
Source File: Engine.java From acunetix-plugin with MIT License | 5 votes |
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 7
Source File: HttpUtil.java From ssrpanel-v2ray with GNU General Public License v3.0 | 5 votes |
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 8
Source File: HttpsClientRequest.java From product-microgateway with Apache License 2.0 | 5 votes |
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 9
Source File: SessionQueryAll.java From pxgrid-rest-ws with Apache License 2.0 | 5 votes |
public static void postAndStreamPrint(HttpsURLConnection httpsConn, Object postObject) throws IOException { Gson gson = new GsonBuilder().registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter()).create(); httpsConn.setRequestMethod("POST"); httpsConn.setRequestProperty("Content-Type", "application/json"); httpsConn.setRequestProperty("Accept", "application/json"); httpsConn.setDoInput(true); httpsConn.setDoOutput(true); OutputStreamWriter osw = new OutputStreamWriter(httpsConn.getOutputStream()); osw.write(gson.toJson(postObject)); osw.flush(); int status = httpsConn.getResponseCode(); logger.info("Response status={}", status); if (status < HttpURLConnection.HTTP_BAD_REQUEST) { try (InputStream in = httpsConn.getInputStream()) { JsonReader jreader = new JsonReader(new InputStreamReader(in)); jreader.beginObject(); String name = jreader.nextName(); if ("sessions".equals(name)) { int count = 0; jreader.beginArray(); while (jreader.hasNext()) { Session session = gson.fromJson(jreader, Session.class); System.out.println("session=" + session); count++; } System.out.println("count=" + count); } } } else { try (InputStream in = httpsConn.getErrorStream()) { String content = IOUtils.toString(in, StandardCharsets.UTF_8); System.out.println("Content: " + content); } } }
Example 10
Source File: MineSkinAPI.java From SkinsRestorerX with GNU General Public License v3.0 | 5 votes |
private String queryURL(String url, String query, int timeout) throws IOException { for (int i = 0; i < 3; i++) { // try 3 times, if server not responding try { MetricsCounter.incrAPI(url); HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-length", String.valueOf(query.length())); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("User-Agent", "SkinsRestorer"); con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.setDoOutput(true); con.setDoInput(true); DataOutputStream output = new DataOutputStream(con.getOutputStream()); output.writeBytes(query); output.close(); String outstr = ""; InputStream _is; try { _is = con.getInputStream(); } catch (Exception e) { _is = con.getErrorStream(); } DataInputStream input = new DataInputStream(_is); for (int c = input.read(); c != -1; c = input.read()) { outstr += (char) c; } input.close(); return outstr; } catch (Exception ignored) { } } return ""; }
Example 11
Source File: RequestUtils.java From ibm-wearables-android-sdk with Apache License 2.0 | 4 votes |
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException { URL url = new URL("https://medge.mybluemix.net/alg/train"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); JSONObject jsonToSend = createTrainBodyJSON(name,uuid,accelerometerData,gyroscopeData); OutputStream outputStream = conn.getOutputStream(); DataOutputStream wr = new DataOutputStream(outputStream); wr.writeBytes(jsonToSend.toString()); wr.flush(); wr.close(); outputStream.close(); String response = ""; int responseCode=conn.getResponseCode(); //Log.e("BBB2","" + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } } else { response="{}"; } handleResponse(response,requestResult); }
Example 12
Source File: WeixinUtil.java From jeewx with Apache License 2.0 | 4 votes |
/** * 发起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 13
Source File: SfmtaApiCaller.java From core with GNU General Public License v3.0 | 4 votes |
/** * 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 14
Source File: EventWriter.java From android-perftracking with MIT License | 4 votes |
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 15
Source File: HttpPOSTRequest.java From main with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected String doInBackground(String... params){ String stringUrl = params[0]; String firstName = params[1]; String lastName = params[2]; String email = params[3]; String password = params[4]; int yearOfBirth = Integer.parseInt(params[5]); JSONObject myjson = new JSONObject(); try { myjson.put("user_first_name", firstName); myjson.put("user_last_name", lastName); myjson.put("user_email", email); myjson.put("user_password", password); myjson.put("user_year_birth", yearOfBirth); URL url = new URL(stringUrl+getPostDataString(myjson)); HttpsURLConnection connection =(HttpsURLConnection) url.openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setDoInput(true); String body = myjson.toString(); OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8")); writer.write(body); writer.flush(); writer.close(); outputStream.close(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); connection.disconnect(); return response.toString(); } catch(Exception e) { return "Exception: " + e.getMessage(); } }
Example 16
Source File: Spotify.java From blade-player with GNU General Public License v3.0 | 4 votes |
private void refreshSpotifyToken() { try { URL apiUrl = new URL("https://accounts.spotify.com/api/token"); HttpsURLConnection urlConnection = (HttpsURLConnection) apiUrl.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); //write POST parameters OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(out, "UTF-8")); writer.write("grant_type=refresh_token&"); writer.write("refresh_token=" + SPOTIFY_REFRESH_TOKEN + "&"); writer.write("client_id=" + SPOTIFY_CLIENT_ID + "&"); writer.write("client_secret=" + "3166d3b40ff74582b03cb23d6701c297"); writer.flush(); writer.close(); out.close(); urlConnection.connect(); System.out.println("[BLADE] [AUTH-REFRESH] Result : " + urlConnection.getResponseCode() + " " + urlConnection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String result = reader.readLine(); reader.close(); result = result.substring(1); result = result.substring(0, result.length()-1); String[] results = result.split(","); for(String param : results) { if(param.startsWith("\"access_token\":\"")) { param = param.replaceFirst("\"access_token\":\"", ""); param = param.replaceFirst("\"", ""); SPOTIFY_USER_TOKEN = param; spotifyApi.setAccessToken(SPOTIFY_USER_TOKEN); SharedPreferences pref = LibraryService.appContext.getSharedPreferences(SettingsActivity.PREFERENCES_ACCOUNT_FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("spotify_token", SPOTIFY_USER_TOKEN); editor.commit(); } } } catch(Exception e) { e.printStackTrace(); } }
Example 17
Source File: HttpsTrustManager.java From stategen with GNU Affero General Public License v3.0 | 4 votes |
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 18
Source File: UnmarkPin.java From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected Void doInBackground(MarkData... params) { Location l = params[0].loc; String username = params[0].username; Context context = params[0].context; Activity activity = params[0].activity; if( username.length() == 0 ) return null; if( l == null ) { Log.d("Unmarking", "Location was null!"); return null; // Location data isn't available yet! } try { List<AbstractMap.SimpleEntry> httpParams = new ArrayList<AbstractMap.SimpleEntry>(); httpParams.add(new AbstractMap.SimpleEntry<>("username", username)); httpParams.add(new AbstractMap.SimpleEntry<>("latitude", Double.valueOf(l.getLatitude()).toString())); httpParams.add(new AbstractMap.SimpleEntry<>("longitude", Double.valueOf(l.getLongitude()).toString())); // Vibrate once, let the user know we received the button tap Vibrate.pulse(context); URL url = new URL("https://" + Constants.DOMAIN + "/unmarkPin"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); try { conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(httpParams)); writer.flush(); writer.close(); os.close(); String response = ""; int responseCode = conn.getResponseCode(); if( responseCode == HttpsURLConnection.HTTP_OK ) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } handleResponse(response, context, activity); Log.d("Unmarking", "Unmarked pin, got response: " + response); } finally { conn.disconnect(); } } catch( Exception e ) { Log.e("UnmarkPin", "Error unmarking pin: " + e.getMessage()); Log.e("UnmarkPin", Log.getStackTraceString(e)); } return null; }
Example 19
Source File: WxstoreUtils.java From jeewx-api with Apache License 2.0 | 4 votes |
public static JSONObject httpRequest2(String requestUrl, String requestMethod, byte[] outputStr) { 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); 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()); } catch (ConnectException ce) { System.out.print("Weixin server connection timed out."); } catch (Exception e) { System.out.print("https request error:{}" + e.getMessage()); } return jsonObject; }
Example 20
Source File: CommonUtil.java From Shop-for-JavaWeb with MIT License | 4 votes |
/** * 发送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; }