I am trying to add google recaptcha in my application. below is the code for validating google captcha.
try {
URL obj = new URL("https://www.google.com/recaptcha/api/siteverify");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Properties properties = System.getProperties();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setConnectTimeout(30 * 1000);
con.setReadTimeout(30 * 1000);
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
if (MyConstants.IS_PROXY_ENABLED) {
properties.put("http.proxyHost",MyConstants.HTTP_PROXY_HOST);
properties.put("http.proxyPort",MyConstants.HTTP_PROXY_PORT);
String authString = MyConstants.HTTP_PROXY_AUTHENTICATION;
String encodedAuthString = "Basic "
+ new sun.misc.BASE64Encoder().encode(authString.getBytes());
con.setRequestProperty("Proxy-authorization",encodedAuthString);
}
// 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 : " + SITE_VERIFY_URL);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
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){
e.printStackTrace();
return false;
}
It is failing with Connection Timeout error every time. I tried to set the timeout but it didn't help.
Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:271)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:778)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:881)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
When i am trying to access https://www.google.com/recaptcha/api/siteverify from browser with input params it gives me result
{
"success": true,
"challenge_ts": "2018-10-12T22:07:18Z",
"hostname": "localhost"
}
Can someone please help me why connection timeout error is coming from code?
Related
I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.
I am working on application to access a web page through vpnbook.com.
My code is sending post request to URL "https://webproxy.vpnbook.com/includes/process.php?action=update" with post body as "u=yahoo.com&webproxylocation=random"
i am getting response code 302. and HTTP response header contains location
"Location=[http://www.vpnbook.com/webproxy]"
But same request was getting correct correct result when opening through web browser.
result contains header response
"Location:https://usproxy.vpnbook.com/browse.phpu=DWnjEwVwhlG5GQhW&b=0&f=norefer"
please tell me what is going wrong in my code.
try{
URL url = new URL("https://webproxy.vpnbook.com/includes/process.php?action=update");
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestProperty("User-Agent", USER_AGENT);
c.setRequestProperty("Accept-Language", ACCEPT_LANG);
c.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
c.setRequestProperty("Host", "webproxy.vpnbook.com");
c.setRequestProperty("Origin", "http://www.vpnbook.com");
c.setRequestProperty("Referer", "http://www.vpnbook.com/webproxy");
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes("u=yahoo.com&webproxylocation=random");
wr.flush();
wr.close();
int responseCode = c.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Response headers : " + c.getHeaderFields());
Map<String, List<String>> resHdr = c.getHeaderFields();
if( resHdr.containsKey("Set-Cookie") ){
cookies=resHdr.get("Set-Cookie").toString();
cookies = cookies.replaceAll("\\[|\\]", "");
System.out.println(cookies);
}
BufferedReader in =
new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
}catch(Exception ex) { ex.printStackTrace(); }
I am trying to send notification message for IOS through GCM from JAVA. That time i am getting one error with 400 status code Bad Request. Below i have mentioned my JAVA code...
String apiKey = "xxxxxxxxxxxxxxxxxxxx"; // Put here your API key
String GCM_Token = regid; // put the GCM Token you want to send to here
String notification = "{\"sound\":\"default\",\"badge\":\"2\",\"title\":\"default\",\"body\":\"Test Push!\"}"; // put the message you want to send here
String messageToSend = "{\"to\":\"" + GCM_Token + "\",\"notification\":" + notification + ",\"content_available\" : true}"; // Construct the message.
TRY{
URL url = new URL("https://android.googleapis.com/gcm/send");
System.out.println("Message"+messageToSend);
// Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Set the headers
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(messageToSend.getBytes("UTF-8"));
//Send the request and close
wr.flush();
wr.close();
//Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Message : " + conn.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//Print result
System.out.println(response.toString()); //this is a good place to check for errors using the codes in http://androidcommunitydocs.com/reference/com/google/android/gcm/server/Constants.html
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
please give me the suggestion.Thanks in advance.
I am using HttpUrlConnection to post some data to my server here is the function:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("strngbuffr" + response.toString());
resp = response.toString();
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
System.out.println("rsp"+ resp.toString());
return resp.toString();
}
I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?
Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"
Its amazing to see, this sample code works - sans the JSON array and the key value pairs:
private String sendPost(String url) throws Exception {
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println("rvsp"+response.toString());
return response.toString();
}
So it boils down to replacing this:
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("key", getencryptkey());
by this:
String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();
and I am still curious.
I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test response");
?>
The problem here was not with the Java side, it was with the php side, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test");
?>
Im trying to access to Google APIs using OAuth 2.0
but i always receive the http 400 when i try to get the token
I'm using Tomcat8 with Java SDK 8
And i don't know what is wrong.
private void sendPost(
final String code,
final String clientId,
final String clientSecret,
final String redirectUri,
final String grantType) throws Exception {
String url = "https://accounts.google.com/o/oauth2/token";
StringBuffer strb = new StringBuffer();
strb.append("code=" + code);
strb.append("&client_id=" + clientId);
strb.append("&client_secret=" + clientSecret);
strb.append("&redirect_uri=" + redirectUri);
strb.append("&grant_type=" + grantType);
String urlParameters = strb.toString();
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
My output is the following it seems that all parameters are ok.
Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400
you'd want to url-encode the parameters
I don't think Google supports redirect_uri's pointing to "localhost" anymore so that would suggest that you got the "code" on a different redirect_uri than the one presented on the token endpoint request