/** * @param url * @param request * @param resContentHeaders * @param timeout * @return * @throws java.lang.Exception * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestoverHTTPS( boolean * isBusReq, URL url, String request, Map resContentHeaders, int timeout)} */ public static String sendRequestOverHTTPS( URL url, String request, Map resContentHeaders, int timeout) throws Exception { // Set up buffers and streams StringBuffer buffy = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection(); urlc.setConnectTimeout(timeout); urlc.setReadTimeout(timeout); urlc.setAllowUserInteraction(false); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); // Set request header properties urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST); urlc.setRequestProperty( FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY, FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE); urlc.setRequestProperty( FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY, String.valueOf(request.length())); // Request // this makes the assumption that all https requests are going to the bus using UTF-8 encoding String encodedString = URLEncoder.encode(request, FastHttpClientConstants.HTTP_REQUEST_ENCODING); out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN); out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes()); out.write(encodedString.getBytes()); out.flush(); // Response // this mangles 2 or more byte characters in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN); buffy = new StringBuffer(INPUT_BUFFER_LEN); int ch = 0; while ((ch = in.read()) > -1) { buffy.append((char) ch); } populateHTTPSHeaderContentMap(urlc, resContentHeaders); } catch (Exception e) { throw e; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (Exception ex) { // Ignore as want to throw exception from the catch block } } return buffy == null ? null : buffy.toString(); }
@Test public void testSendMessage() throws Exception { String url = getAppBaseURL() + "send_message"; URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); String body = "message=" + URLEncoder.encode(MESSAGE, "UTF-8"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); // It ensures that the app successfully received the message. assertEquals(204, responseCode); // Try fetching the /fetch_messages endpoint and see if the // response contains the message. boolean found = false; for (int i = 0; i < MAX_RETRY; i++) { Thread.sleep(SLEEP_TIME); String resp = fetchMessages(); if (resp.contains(MESSAGE)) { found = true; break; } } assertTrue(found); }
/** * Parses the url connection. * * @param url the url * @param apiKey the api key * @param requestMethod the request method * @param data the data * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws JSONException the jSON exception */ public static String parseUrlConnection(String url, String requestMethod, String data) throws IOException, JSONException { URL u = new URL(url); HttpsURLConnection uc = (HttpsURLConnection) u.openConnection(); uc.setRequestMethod(requestMethod); String authentication = "<DocuSignCredentials><Username>" + Data.USERNAME + "</Username><Password>" + Data.PASSWORD + "</Password><IntegratorKey>" + Data.INTEGRATOR_KEY + "</IntegratorKey></DocuSignCredentials>"; uc.setRequestProperty("X-DocuSign-Authentication", authentication); uc.setRequestProperty("Content-type", "application/json"); uc.setRequestProperty("Accept", "application/json"); if (data != null) { uc.setDoOutput(true); OutputStreamWriter postData = new java.io.OutputStreamWriter(uc.getOutputStream()); postData.write(data); postData.flush(); postData.close(); } InputStream is = uc.getInputStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); return jsonText; } finally { is.close(); } }
/** * Synchronous call for logging in * * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException { String response = ""; URL url = new URL(WebServiceAuthProvider.tokenURL()); HttpsURLConnection connection = createSecureConnection(url); String authString = "mobile_android:secret"; String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e( LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } return response; }
public String doPost(String urlstr, byte data[]) throws IOException { URL url = new URL(urlstr); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); fetchReqMap(connection); // // connection.setRequestProperty("SOAPAction","https://hms.wellcare.cn:8443/services/EnergyData"); connection.setReadTimeout(timeout); connection.setDoOutput(true); // true for POST, false for GET connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); // 写入post数据 OutputStream out = connection.getOutputStream(); out.write(data); // 读出反馈结果 String aLine = null; String ret = ""; InputStream is = connection.getInputStream(); BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode())); while ((aLine = aReader.readLine()) != null) { ret += aLine + "\r\n"; } aReader.close(); connection.disconnect(); return ret; }
// Add a new user public String addUser(String uri, String j) { try { URL url = new URL(uri); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(j); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } Log.d("AddUserReponse", response.toString()); in.close(); return "success"; } catch (Exception e) { e.printStackTrace(); return "fail"; } }
public String doGet(String urlstr) throws IOException { URL url = new URL(urlstr); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); fetchReqMap(connection); // 设置请求属性 connection.setReadTimeout(timeout); connection.setDoOutput(false); // true for POST, false for GET connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setUseCaches(false); String aLine = null; String ret = ""; InputStream is = connection.getInputStream(); BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode())); while ((aLine = aReader.readLine()) != null) { ret += aLine + "\r\n"; ; } aReader.close(); connection.disconnect(); return ret; }
/** * HttpUrlConnection支持所有Https免验证,不建议使用 * * @throws KeyManagementException * @throws NoSuchAlgorithmException * @throws IOException */ public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException { URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version"); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] {new TrustAllManager()}, null); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); connection.connect(); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; StringBuffer result = new StringBuffer(); while ((line = reader.readLine()) != null) { result.append(line); } String reString = result.toString(); Log.i("TTTT", reString); }
@Override public String receiveData(String urlPath, String streamData) { StringBuilder responseStringBuilder = new StringBuilder(); URL url = null; URLConnection urlConnection = null; Scanner scanner = null; try { url = new URL(urlPath); urlConnection = url.openConnection(); HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection; httpsUrlConnection.setDoOutput(true); httpsUrlConnection.setDoInput(true); httpsUrlConnection.setUseCaches(false); httpsUrlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); httpsUrlConnection.setRequestMethod("POST"); httpsUrlConnection.connect(); if (streamData != null) { OutputStream outputStream = httpsUrlConnection.getOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); outputStreamWriter.write(streamData); outputStreamWriter.flush(); outputStreamWriter.close(); } scanner = new Scanner(urlConnection.getInputStream(), "UTF-8"); while (scanner.hasNext()) { String tempString = scanner.nextLine().trim(); responseStringBuilder.append(tempString); } scanner.close(); } catch (Exception e) { return null; } return responseStringBuilder.toString(); }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } // Send HTTP POST request to server URL url = new URL("https://localhost:" + serverPort); HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier()); HttpsURLConnection http = (HttpsURLConnection) url.openConnection(); http.setDoOutput(true); http.setRequestMethod("POST"); PrintStream ps = new PrintStream(http.getOutputStream()); try { ps.println(postMsg); ps.flush(); if (http.getResponseCode() != 200) { throw new RuntimeException("test Failed"); } } finally { ps.close(); http.disconnect(); closeReady = true; } }
/** * Executa a operação da API informando um Builder para a requisição e resposta. * * @param requestBuilder é uma instância de {@link AkatusRequestBuilder} responsável pela criação * do corpo da requisição. * @param responseBuilder é uma instância de {@link AkatusResponseBuilder} responsável pela * criação do objeto que representa a resposta. * @return Uma instância de {@link AkatusResponse} com a resposta da operação. */ public AkatusResponse execute( AkatusRequestBuilder requestBuilder, AkatusResponseBuilder responseBuilder) { AkatusResponse response = new AkatusResponse(); try { final URL url = new URL(akatus.getHost() + getPath()); final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", requestBuilder.getContentType()); final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestBuilder.build(this)); writer.flush(); try { response = responseBuilder.build(readResponse(connection.getInputStream())); } catch (final IOException e) { response = responseBuilder.build(readResponse(connection.getErrorStream())); } } catch (final Exception e) { Logger.getLogger(AkatusOperation.class.getName()) .throwing(this.getClass().getName(), "execute", e); } return response; }
/** * 方法名:httpRequest</br> 详述:发送http请求</br> 开发人员:souvc </br> 创建时间:2016-1-5 </br> * * @param requestUrl * @param requestMethod * @param outputStr * @return 说明返回值含义 * @throws 说明发生此异常的条件 */ private static JsonNode httpRequest(String requestUrl, String requestMethod, String outputStr) { StringBuffer buffer = new StringBuffer(); JsonNode josnNode = null; JSONObject jsonObject = null; try { URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setRequestMethod("GET"); httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒 httpUrlConn.connect(); 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); } josnNode = new ObjectMapper().readTree(buffer.toString()); bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; httpUrlConn.disconnect(); } catch (ConnectException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return josnNode; }
public static String httsRequest(String url, String contentdata) { String str_return = ""; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { sc.init( null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } URL console = null; try { console = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection conn; try { conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("POST"); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json" String inpputs = contentdata; OutputStream os = conn.getOutputStream(); os.write(inpputs.getBytes()); os.close(); conn.connect(); InputStream is = conn.getInputStream(); // // DataInputStream indata = new DataInputStream(is); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String ret = ""; while (ret != null) { ret = reader.readLine(); if (ret != null && !ret.trim().equals("")) { str_return = str_return + ret; } } is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str_return; }
public static String sendRequestOverHTTPS( boolean isBusReq, URL url, String request, Map resContentHeaders, int timeout) throws Exception { // Set up buffers and streams BufferedOutputStream out = null; BufferedInputStream in = null; String fullResponse = null; try { HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection(); urlc.setConnectTimeout(timeout); urlc.setReadTimeout(timeout); urlc.setAllowUserInteraction(false); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); // Set request header properties urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST); urlc.setRequestProperty( FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY, FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE); urlc.setRequestProperty( FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY, String.valueOf(request.length())); // Request out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN); sendRequestString(isBusReq, out, request); // recv response in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN); String contentType = urlc.getHeaderField("Content-Type"); fullResponse = receiveResponseString(in, contentType); out.close(); in.close(); populateHTTPSHeaderContentMap(urlc, resContentHeaders); } catch (Exception e) { throw e; } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (Exception ex) { // Ignore as want to throw exception from the catch block } } return fullResponse; }
public JSONObject httpsRequest(String requestUrl, String httpMethod, String defaultStr) { JSONObject res = new JSONObject(); try { TrustManager[] tm = {new MyX509TrustManager()}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new SecureRandom()); SSLSocketFactory sf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sf); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod(httpMethod); if (defaultStr != null) { OutputStream os = conn.getOutputStream(); os.write(defaultStr.getBytes("UTF-8")); os.close(); } InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); BufferedReader br = new BufferedReader(isr); String str = null; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); } br.close(); isr.close(); is.close(); is = null; conn.disconnect(); res = JSONObject.fromObject(sb.toString()); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; }
/** * 发起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; // log.info("https请求url是" + requestUrl); 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; StringBuffer buffer = new StringBuffer(); 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) { log.error("连接超时", ce); } catch (Exception e) { log.error("请求异常", e); } return jsonObject; }
private void testIt() { String https_url = requestURL; URL url; SSLSocketFactory socketFactory = null; try { try { socketFactory = createSSLContext().getSocketFactory(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } url = new URL(https_url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setSSLSocketFactory(socketFactory); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); conn.addRequestProperty("app_id", app_id); conn.addRequestProperty("app_key", app_key); // dump all cert info // print_https_cert(con); // dump all the content print_content(conn); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static String httpsRequestByWx(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 conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 设置请求方式(GET/POST) conn.setRequestMethod(requestMethod); // 当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; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } // 释放资源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; conn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { logger.error("连接超时:{}", ce); } catch (Exception e) { logger.error("https请求异常:{}", e); } return buffer.toString(); }
protected static String getResponseForXPayToken( String endpoint, String xpaytoken, String payload, String method, String crId) throws IOException { logRequestBody(payload, endpoint, xpaytoken, crId); HttpsURLConnection conn = null; OutputStream os; BufferedReader br = null; InputStream is; String output; String op = ""; URL url1 = new URL(endpoint); // getCertificate(); conn = (HttpsURLConnection) url1.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("x-request-id", "1234"); conn.setRequestProperty("x-pay-token", xpaytoken); conn.setRequestProperty("X-CORRELATION-ID", crId); if (!StringUtils.isEmpty(payload)) { os = conn.getOutputStream(); os.write(payload.getBytes()); os.flush(); } if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { is = conn.getInputStream(); } if (is != null) { br = new BufferedReader(new InputStreamReader(is)); while ((output = br.readLine()) != null) { op += output; } } // Log the response Headers Map<String, List<String>> map = conn.getHeaderFields(); // for (Map.Entry<String, List<String>> entry : map.entrySet()) { logger.info("Response Headers: " + map.toString()); // } conn.disconnect(); logResponseBody(op); return op; }
public static boolean verify(String gRecaptchaResponse) throws IOException { if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) { return false; } try { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); // add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(postParams); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + postParams); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result System.out.println(response.toString()); // parse JSON response and return 'success' value JsonReader jsonReader = Json.createReader(new StringReader(response.toString())); JsonObject jsonObject = jsonReader.readObject(); jsonReader.close(); return jsonObject.getBoolean("success"); } catch (Exception e) { return false; } }
/** * if the barcode hasn't already got a name on outpan.com the item will be listed online with the * passed name * * @param gtin * @param name */ private void listNewItem(String gtin, String name) { try { URL url = new URL( "https://api.outpan.com/v2/products/" + gtin + "/name" + "?apikey=e13a9fb0bda8684d72bc3dba1b16ae1e"); HttpsURLConnection httpCon = (HttpsURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); // replaces umlauts, ß, ", ' and / name = IllegalStringReplacer.replaceIllegalChars(name); String content = "name=" + name; DataOutputStream out = new DataOutputStream(httpCon.getOutputStream()); out.writeBytes(content); out.flush(); log.debug(httpCon.getResponseCode() + " - " + httpCon.getResponseMessage()); out.close(); if (httpCon.getResponseCode() == 200) { Alert alert = Alerter.getAlert(AlertType.INFORMATION, "Item Added", null, "Item is now listed."); alert.showAndWait(); log.info("Item '" + name + "' now listed"); addItem(gtin); } else { log.debug("Item could not be listed"); Alert alert = Alerter.getAlert( AlertType.WARNING, "Item not Added", null, "Item could not be listed, please try again."); alert.showAndWait(); } } catch (MalformedURLException e) { log.error("MalformedURLException: " + e.getMessage()); } catch (IOException e) { log.error("IOException: " + e.getMessage()); } }
public static Object ConnectToServer( URL url, String jsoninput, boolean hasinput, boolean hasoutput, String requestMethod) { try { HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(ssf); con.setDoInput(true); con.setRequestMethod(requestMethod); OutputStream os = null; StringBuffer sb = null; StringBuffer log = new StringBuffer(); log.append(requestMethod).append(":"); log.append("url=").append(url).append("."); if (hasinput) { log.append("jsoninput=").append(jsoninput).append("."); if (jsoninput == null) { log.append("parameter error."); logger.error(log.toString()); } con.setDoOutput(true); os = con.getOutputStream(); os.write(jsoninput.getBytes()); os.close(); } if (hasoutput) { InputStream is = con.getInputStream(); InputStreamReader inputstreamReader = new InputStreamReader(is); BufferedReader bufferedreader = new BufferedReader(inputstreamReader); String str = null; sb = new StringBuffer(); while ((str = bufferedreader.readLine()) != null) { sb.append(str); } bufferedreader.close(); inputstreamReader.close(); is.close(); } con.disconnect(); return sb.toString(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
private void GetHttps() { String https = "https://mail.qq.com/cgi-bin/loginpage"; try { HttpsURLConnection conn = (HttpsURLConnection) new URL(https).openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) sb.append(line); Log.e("testcaseLog", sb.toString()); } catch (Exception e) { e.printStackTrace(); } }
/** * 模拟http请求 * * @param requestUrl URL * @return */ private static JSONObject httpRequest(String requestUrl) { // TODO Auto-generated method stub JSONObject jsonObject = null; String requestMethod = "GET"; StringBuffer buffer = new StringBuffer(); try { TrustManager[] tm = {new MyX509TrustManager()}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.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(); 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) { log.error("http请求数据失败�?" + ce.getMessage()); } catch (Exception e) { log.error("http请求数据失败�?" + e.getMessage()); } return jsonObject; }
/** * GET请求 * * @param url URL * @return 返回结果 * @throws IOException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String get(String url) throws IOException, NoSuchAlgorithmException, KeyManagementException { SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(null, new TrustManager[] {trustManager}, null); HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("GET"); conn.setSSLSocketFactory(ssl.getSocketFactory()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = in.readLine()) != null) { sb.append(line); } conn.disconnect(); return sb.toString(); }
private static HttpsURLConnection sendSecureHttpsConnection(HttpsURLConnection conn, String data) throws IOException { BufferedWriter bw = null; try { conn.setDoOutput(true); bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); bw.write(data); bw.flush(); bw.close(); return conn; } catch (IOException e) { log4j.error(e.getMessage(), e); throw e; } }
// Update a field in a record given REST URL public boolean updateField(String uri, String j) { try { URL url = new URL(uri); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(j); out.close(); con.getInputStream(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken) throws IOException { HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection(); nection.setDoInput(true); nection.setDoOutput(true); nection.setRequestProperty("Content-Type", "application/json"); nection.setRequestProperty("Accept", "application/json"); nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME); if (accessToken != null) { nection.setRequestProperty("Authorization", "token " + accessToken); } OutputStream os = nection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); os.close(); try { nection.connect(); InputStream in = new BufferedInputStream(nection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); while (true) { String line = reader.readLine(); if (line == null) { break; } response.append(line); } try { return new JSONObject(response.toString()); } catch (JSONException e) { throw new IOException(e); } } finally { nection.disconnect(); } }
public HttpsURLConnection openConnection() throws IOException { HttpsURLConnection connection = null; try { if (!isPost) { // 如果是get请求则拼接URL地址,一般情况下不会走https的get请求 mUrl += packageTextParamsForGet(); } // 初始化连接 URL connecter = new URL(mUrl); connection = (HttpsURLConnection) connecter.openConnection(); // 设置安全套接工厂 connection.setSSLSocketFactory(mSslContext.getSocketFactory()); connection.setConnectTimeout(TIME_OUT); connection.setReadTimeout(TIME_OUT); // connection.setRequestProperty("User-Agent", // "Mozilla/5.0 ( compatible ) "); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "*/*;charset=UTF-8"); connection.setRequestProperty("Connection", "Keep-Alive"); if (isPost) { connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); } // 设置输入输出流 connection.setDoInput(true); if (isPost) connection.setDoOutput(true); } catch (IOException ioe) { throw ioe; } // 查询params里面是否有数据 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : mParams.entrySet()) sb.append(entry.getValue() + LINE_END); // 向输入流里面写入,需要提交的数据 out.write(sb.toString().getBytes()); out.flush(); out.close(); return connection; }
/** * http post 请求 * * @param url 请求url * @param jsonStr post参数 * @return HttpResponse请求结果实例 */ public static Response httpPost(String url, String jsonStr) { Response response = null; HttpsURLConnection httpsURLConnection = null; try { URL urlObj = new URL(url); httpsURLConnection = (HttpsURLConnection) urlObj.openConnection(); httpsURLConnection.setRequestMethod("POST"); httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout); httpsURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); httpsURLConnection.setDoOutput(true); httpsURLConnection.setChunkedStreamingMode(0); // start to post response = writeStream(httpsURLConnection, jsonStr); if (response == null) { // if post successfully response = readStream(httpsURLConnection); } } catch (MalformedURLException e) { e.printStackTrace(); response = new Response(); response.content = e.getMessage(); response.code = -1; } catch (IOException e) { e.printStackTrace(); response = new Response(); response.content = e.getMessage(); response.code = -1; } catch (Exception ex) { ex.printStackTrace(); response = new Response(); response.content = ex.getMessage(); response.code = -1; } finally { if (httpsURLConnection != null) httpsURLConnection.disconnect(); } return response; }