Java Code Examples for javax.net.ssl.HttpsURLConnection#HTTP_OK

The following examples show how to use javax.net.ssl.HttpsURLConnection#HTTP_OK . 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: CustomHandler.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(final Message message) throws Fault {
    if (isResponseAlreadyHandled(message)) {
        return;
    }
    final MessageContentsList objs = MessageContentsList.getContentsList(message);
    if (objs == null || objs.isEmpty()) {
        return;
    }

    final Object responseObj = objs.get(0);
    if (Response.class.isInstance(responseObj)) {
        final Response response = Response.class.cast(responseObj);
        if (is404(message, response)) {
            switchResponse(message);
        }
    } else {
        final Object exchangeStatus = message.getExchange().get(Message.RESPONSE_CODE);
        final int status = exchangeStatus != null ? Integer.class.cast(exchangeStatus) : HttpsURLConnection.HTTP_OK;
        if (status == HttpsURLConnection.HTTP_NOT_FOUND) {
            switchResponse(message);
        }
    }
}
 
Example 2
Source File: WebService.java    From webi with Apache License 2.0 6 votes vote down vote up
private String readHttpConnection(HttpURLConnection httpURLConnection) {
    final StringBuilder stringBuilder = new StringBuilder();

    int code = 0;
    try {
        code = httpURLConnection.getResponseCode();
        onInfo("response code = " + code + " : " + new HttpCode().httpCode(code));
        if (code == HttpsURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
        } else {
            webiEvents.OnFailed(code);
            onError("httpURLConnection is not 200 or OK");
        }
        return stringBuilder.toString();
    } catch (Exception e) {
        onError(e.getMessage());
        return "";
    }
}
 
Example 3
Source File: RandomOrgClient.java    From JSON-RPC-Java with MIT License 5 votes vote down vote up
/** POST JSON to server and return JSON response.
 ** 
 ** @param json request to post. 
 **
 ** @return JSON response.
 **
 ** @throws IOException @see java.io.IOException
 ** @throws MalformedURLException in the unlikely event something goes wrong with URL creation. @see java.net.MalformedURLException
 ** @throws RandomOrgBadHTTPResponseException if a HTTP 200 OK response not received.
 **/
private JsonObject post(JsonObject json) throws IOException, MalformedURLException, RandomOrgBadHTTPResponseException {

	HttpsURLConnection con = (HttpsURLConnection) new URL("https://api.random.org/json-rpc/1/invoke").openConnection();
	con.setConnectTimeout(this.httpTimeout);

	// headers		
	con.setRequestMethod("POST");
	con.setRequestProperty("Content-Type", "application/json");
	
	// send JSON
	con.setDoOutput(true);
	DataOutputStream dos = new DataOutputStream(con.getOutputStream());
	dos.writeBytes(json.toString());
	dos.flush();
	dos.close();

	// check response
	int responseCode = con.getResponseCode();
	
	// return JSON...
	if (responseCode == HttpsURLConnection.HTTP_OK) {
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		return new JsonParser().parse(response.toString()).getAsJsonObject();
		
	// ...or throw error
	} else {
		throw new RandomOrgBadHTTPResponseException("Error " + responseCode + ": " + con.getResponseMessage());
	}
}
 
Example 4
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 5
Source File: SdkTest.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
private void checkPrebidLog() {
    if (!mInitialPrebidServerResponseReceived) {
        BidLog.BidLogEntry entry = BidLog.getInstance().getLastBid();

        if (mListener != null) {
            if (entry != null) {
                if (entry.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                    mListener.responseFromPrebidServerReceived(true);
                    if (entry.containsTopBid()) {
                        mListener.bidReceivedAndCached(true);
                    } else {
                        mListener.bidReceivedAndCached(false);
                    }
                } else {
                    mListener.responseFromPrebidServerReceived(false);
                    mListener.bidReceivedAndCached(false);
                }
            } else {
                mListener.responseFromPrebidServerReceived(false);
                mListener.bidReceivedAndCached(false);
            }
        }

        BidLog.getInstance().cleanLog();

        mInitialPrebidServerResponseReceived = true;
    }
}
 
Example 6
Source File: AuthEndpoint.java    From taiga-android with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthResponse doInBackground(String... params) {
    try {
        URL url = new URL(taigaUrl + "/api/v1/auth");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        String postData = String.format("type=normal&username=%s&password=%s",
                URLEncoder.encode(username, "UTF-8"), URLEncoder.encode(password, "UTF-8"));

        try (OutputStream os = conn.getOutputStream();
             OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
             BufferedWriter writer = new BufferedWriter(out)) {
            writer.write(postData);
            writer.flush();
        }
        int responseCode = conn.getResponseCode();

        Log.w(TAG, "Login response code: " + responseCode);
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String jsonResponse = IOUtils.toString(conn.getInputStream());
            Log.d(TAG, "Login response: " + jsonResponse);

            return new GsonBuilder().create().fromJson(jsonResponse, AuthResponse.class);
        }
        throw new IllegalStateException(String.valueOf(responseCode));
    } catch (Exception e) {
        Log.e(TAG, "Error requesting login", e);
        return null;
    }
}
 
Example 7
Source File: GetIp.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected String doInBackground(String... params) {

    try
    {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader input = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
        ip = input.readLine();

        HttpURLConnection connection = (HttpURLConnection) new URL("http://ip-api.com/json/" + ip).openConnection();
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
        //s=readStream(in,10000);
        s=convertStreamToString(in);

        Log.d("MainActivity", "Call reached here");

        if (in != null) {
            // Converts Stream to String with max length of 500.
            Log.d("MainActivity call 2", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return s;
}
 
Example 8
Source File: FeedBackActivityFragment.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected String doInBackground(String... params)
{

    try
    {
        String p1 = URLEncoder.encode(nameValue,"utf-8");
        String p2 = URLEncoder.encode(messageValue,"utf-8");
        String ur = "http://akash-deep.in/contact-process.jsp?" +
                "Name="+p1+"&Email="+emailvalue+"&phone="+phoneValue+"&Message="+p2+"";
        HttpURLConnection connection = (HttpURLConnection) new URL(ur).openConnection();
     //   Toast.makeText(getActivity(),ur,Toast.LENGTH_SHORT).show();
        Log.d("myurla",ur);
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
        s = convertStreamToString(in);
        //pd.dismiss();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return s;
}
 
Example 9
Source File: IpDetailsFragment.java    From Cybernet-VPN with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected String doInBackground(String... params) {

    try
    {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader input = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
        ip = input.readLine();

        HttpURLConnection connection = (HttpURLConnection) new URL("http://ip-api.com/json/" + ip).openConnection();
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
        //s=readStream(in,10000);
        s=convertStreamToString(in);
        jsonObject=new JSONObject(s);

        city=jsonObject.getString("city");
        isp=jsonObject.getString("org");
        state=jsonObject.getString("regionName");
        country=jsonObject.getString("country");

        Log.d("MainActivity", "Call reached here");

        if (in != null) {
            // Converts Stream to String with max length of 500.
            Log.d("MainActivity call 2", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return s;
}
 
Example 10
Source File: GoogleElevationApi.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void getElevation(Location location, Context context) throws IOException, JSONException {
    // https://developers.google.com/maps/documentation/elevation/
    URL url = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations=" +
            String.valueOf(location.getLatitude()) + "," +
            String.valueOf(location.getLongitude()) +
            "&key=AIzaSyAp0gtiT6AqaSUSlqwXSyoFCA6SCzMyr6w");
    Log.d(TAG, "url=" + url);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();

    urlConnection.setConnectTimeout(cTimeOutMs);
    urlConnection.setReadTimeout(cTimeOutMs);
    urlConnection.setRequestProperty("Accept", "application/json");

    // Set request type
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(false);
    urlConnection.setDoInput(true);

    try {
        // Check for errors
        int code = urlConnection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_OK)
            throw new IOException("HTTP error " + urlConnection.getResponseCode());

        // Get response
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder json = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null)
            json.append(line);
        Log.d(TAG, json.toString());

        // Decode result
        JSONObject jroot = new JSONObject(json.toString());
        String status = jroot.getString("status");
        if ("OK".equals(status)) {
            JSONArray results = jroot.getJSONArray("results");
            if (results.length() > 0) {
                double elevation = results.getJSONObject(0).getDouble("elevation");
                location.setAltitude(elevation);
                Log.i(TAG, "Elevation " + location);
            } else
                throw new IOException("JSON no results");
        } else
            throw new IOException("JSON status " + status);
    } finally {
        urlConnection.disconnect();
    }
}
 
Example 11
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 12
Source File: JSONImageFetcher.java    From glide-support with The Unlicense 4 votes vote down vote up
@Override public InputStream loadData(Priority priority) throws Exception {
	// This implementation is totally up to you
	// TODO produce an InputStream that contains the raw image bytes that can be decoded (below is just an example)
	URL url = new URL(model.getUri());
	conn = (HttpURLConnection)url.openConnection();
	try {
		conn.setReadTimeout(15000);
		conn.setConnectTimeout(15000);
		conn.setRequestMethod("POST");
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "application/json");

		JSONObject payload = model.getPayload();
		// TODO remove this, only for testing with httpbin to have a proper response
		payload.put("imageData", "data:image/png,base64," + App.getInstance().getString(R.string.glide_base64));
		OutputStream request = conn.getOutputStream();
		try {
			request.write(payload.toString().getBytes("UTF-8"));
		} finally {
			request.close();
		}
		int responseCode = conn.getResponseCode();
		if (responseCode == HttpsURLConnection.HTTP_OK) {
			response = conn.getInputStream();
			try {
				JSONObject object = readJSON(response);
				// TODO remove this, only needed for testing with httpbin
				object = new JSONObject(object.getString("data"));
				String dataUri = object.getString("imageData");
				String base64 = dataUri.substring("data:image/png,base64,".length());
				byte[] raw = Base64.decode(base64, Base64.NO_WRAP);
				return new ByteArrayInputStream(raw);
			} finally {
				response.close();
			}
		} else {
			throw new IOException("Invalid response: " + responseCode);
		}
	} finally {
		conn.disconnect();
	}
}
 
Example 13
Source File: MarkOrVerifyPin.java    From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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("Marking", "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 + "/markPin");
        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("Marking", "Marked new pin, got response: " + response);
        } finally {
            conn.disconnect();
        }
    } catch( Exception e ) {
        Log.e("MarkPin", "Error marking pin: " + e.getMessage());
        Log.e("MarkPin", Log.getStackTraceString(e));
    }
    return null;
}
 
Example 14
Source File: UnmarkPin.java    From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@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 15
Source File: RequestUtils.java    From ibm-wearables-android-sdk with Apache License 2.0 4 votes vote down vote up
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 16
Source File: BaiduPushUtil.java    From OneBlog with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 推送链接到百度站长平台
 *
 * @param urlString 百度站长平台地址
 * @param params    待推送的链接
 * @param cookie    百度平台的cookie
 * @return api接口响应内容
 */
public static String doPush(String urlString, String params, String cookie) {
    if (StringUtils.isEmpty(cookie)) {
        throw new ZhydCommentException("尚未设置百度站长平台的Cookie信息,该功能不可用!");
    }
    log.info("{} REST url: {}", new Date(), urlString);
    HttpURLConnection connection = null;
    try {
        connection = openConnection(urlString);
        connection.setRequestMethod("POST");
        // (如果不设此项,json数据 ,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Action", "1000");
        connection.setRequestProperty("User-Agent", USER_AGENT);
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Cookie", cookie);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        // 设置连接超时时间,单位毫秒
        connection.setConnectTimeout(10000);
        // 设置读取数据超时时间,单位毫秒
        connection.setReadTimeout(10000);
        // Post 请求不能使用缓存
        connection.setUseCaches(false);
        if (params != null) {
            final OutputStream outputStream = connection.getOutputStream();
            writeOutput(outputStream, params);
            outputStream.close();
        }
        log.info("RestClientUtil response: {} : {}", connection.getResponseCode(), connection.getResponseMessage());
        if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
            return readInput(connection.getInputStream(), "UTF-8");
        } else {
            return readInput(connection.getErrorStream(), "UTF-8");
        }
    } catch (Exception e) {
        log.error("推送到百度站长平台发生异常!", e);
        return "";
    } finally {
        if (null != connection) {
            connection.disconnect();
        }
    }
}
 
Example 17
Source File: MainFragment.java    From Cybernet-VPN with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected String doInBackground(String... params) {

    try
    {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader input = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
        ip = input.readLine();

        HttpURLConnection connection = (HttpURLConnection) new URL("http://ip-api.com/json/" + ip).openConnection();
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
        //s=readStream(in,10000);
        s=convertStreamToString(in);
        jsonObject=new JSONObject(s);

        city=jsonObject.getString("city");
        isp=jsonObject.getString("org");
        state=jsonObject.getString("regionName");
        country=jsonObject.getString("country");

        Log.d("MainActivity", "Call reached here");

        if (in != null) {
            // Converts Stream to String with max length of 500.
            Log.d("MainActivity call 2", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return s;
}
 
Example 18
Source File: OpenIDConnectAuthenticator.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Refreshes the OpenID Connect id_token
 *
 * @param clientId from client-id
 * @param refreshToken from refresh-token
 * @param clientSecret from client-secret
 * @param sslContext to support TLS with a self signed certificate in
 *     idp-certificate-authority-data
 * @param tokenURL the url for refreshing the token
 * @return
 */
private JSONObject refreshOidcToken(
    String clientId,
    String refreshToken,
    String clientSecret,
    SSLContext sslContext,
    String tokenURL) {
  try {
    URL tokenEndpoint = new URL(tokenURL);
    HttpsURLConnection https = (HttpsURLConnection) tokenEndpoint.openConnection();
    https.setRequestMethod("POST");
    if (sslContext != null) {
      https.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    // per https://tools.ietf.org/html/rfc6749#section-2.3 the secret should be a header, not in
    // the body
    String credentials =
        Base64.getEncoder()
            .encodeToString(
                new StringBuilder()
                    .append(clientId)
                    .append(':')
                    .append(clientSecret)
                    .toString()
                    .getBytes("UTF-8"));
    https.setRequestProperty(
        "Authorization", new StringBuilder().append("Basic ").append(credentials).toString());
    https.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    https.setDoOutput(true);

    String urlData =
        new StringBuilder()
            .append("refresh_token=")
            .append(URLEncoder.encode(refreshToken, "UTF-8"))
            .append("&grant_type=refresh_token")
            .toString();
    OutputStream ou = https.getOutputStream();
    ou.write(urlData.getBytes("UTF-8"));
    ou.flush();
    ou.close();

    int code = https.getResponseCode();

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

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

    return (JSONObject) new JSONParser().parse(json);

  } catch (Throwable t) {
    throw new RuntimeException("Could not refresh token", t);
  }
}
 
Example 19
Source File: RestClientUtil.java    From OneBlog with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param method:
 *         GET/PUT/POST default GET
 * @param urlString:
 *         requried
 * @param params:
 *         default null
 */
public static String request(String method, String urlString, Map<String, Object> params, String encode, Map<String, String> requestHeader) {
    // 解决因jdk版本问题造成的SSL请求失败的问题
    java.lang.System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
    final HttpURLConnection connection;
    try {
        connection = openConnection(urlString);
        connection.setRequestMethod(method);
        if (null != requestHeader) {
            Set<Map.Entry<String, String>> entrySet = requestHeader.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        } else {
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("User-Agent", USER_AGENT);
        }
        connection.setDoOutput(true);

        if (!CollectionUtils.isEmpty(params)) {
            final OutputStream outputStream = connection.getOutputStream();
            StringBuilder paramsStr = new StringBuilder();
            Set<Map.Entry<String, Object>> set = params.entrySet();
            for (Map.Entry<String, Object> stringObjectEntry : set) {
                paramsStr.append(stringObjectEntry.getKey()).append("=").append(stringObjectEntry.getValue()).append("&");
            }
            paramsStr.setLength(paramsStr.length() - 1);
            writeOutput(outputStream, paramsStr.toString());
            outputStream.close();
        }

        log.info("RestClientUtil url: {}, response: {} : {}", urlString, connection.getResponseCode(), connection.getResponseMessage());

        if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
            return readInput(connection.getInputStream(), encode);
        } else {
            return readInput(connection.getErrorStream(), encode);
        }
    } catch (Exception e) {
        log.error("Http请求失败{}", urlString, e);
    }
    return null;
}