Im trying to get a timestamp from a tsa server and I got this error. I dont know where is the problem.
java.lang.IllegalArgumentException: unknown object in 'TimeStampResp' factory : org.bouncycastle.asn1.DERUnknownTag
In this statement
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
This is my code:
String TSA_URL = "http://tsa.starfieldtech.com/";
//String TSA_URL = "http://ca.signfiles.com/TSAServer.aspx";
//String TSA_URL = "http://timestamping.edelweb.fr/service/tsp";
try {
//byte[] digest = calcularMessageDigest(leerByteFichero("C:\\deskSign.txt"));
byte[] digest = leerByteFichero("C:\\deskSign.txt");
TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
TimeStampRequest req = reqgen.generate(TSPAlgorithms.SHA1, digest);
byte request[] = req.getEncoded();
URL url = new URL(TSA_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type:", "application/timestamp-query");
con.setRequestProperty("Content-length:", String.valueOf(request.length));
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
response.validate(req);
System.out.println(response.getTimeStampToken().getTimeStampInfo().getGenTime());
Anyone can help me?
You made two errors:
No colons after Content-type and Content-length
You forgot to actually send the request
Here is and adaptation of your code that works:
TimeStampRequest request;
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/timestamp-query");
con.setRequestProperty("Content-length", String.valueOf(request.getEncoded().length));
Authenticator.setDefault(new Authenticator() {
con.getOutputStream().write(request.getEncoded());
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
Related
I need to convert below Swift code to Java.
Swift code works.
But, Java code is not worked.
HttpsURLConnection has failed.
responseCode: 400 (HttpsURLConnection.getResponseCode())
message2: Bad Request (HttpsURLConnection.getResponseMessage())
How can I solve 400 Bad Request error.
In Swift(It worked)
func sendNotification(token: String, message: String) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(firebaseServerKey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"body\":\"\(message)\",\"badge\":\"1\"}}".data(using: .utf8)
}
I wrote in JAVA(not worked)
private void sendNotification(String token, String message) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+firebaseServerKey);
String str = "{\"to\": " + token + ", \"notification\": { \"body\": " + message + ", \"badge\": \"1\"}}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
int responseCode = conn.getResponseCode(); // responseCode: 400
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.d("Success", String.valueOf(responseCode));
} else {
String code = String.valueOf(responseCode);
String message2 = conn.getResponseMessage(); // message2: Bad Request
Log.d("Fail", String.valueOf(responseCode));
Log.d("Fail2", conn.getResponseMessage());
}
}
Your JSON request body is incorrect. It produce {"to": zxc} which is an invalid json. Change it to
String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
message + "\", \"badge\": \"1\"}}";
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?
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 have to automate API through selenium+TestNG (Java). I know its not a good habit to automate APIs using selenium code but still I have got this to do.
Scenario - there is a login API and have to send the email and password and get response back (response code 200). Also can we print the response information also?
If you are working on java you can use JAVA socket libraries for the same:
Here are the sample code for POST API:
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
String urlParameters = "j_username=" + user + "&j_password=" + pass
+ "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
For GET API:
obj = new URL(url);
obj.openConnection();
con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
CookieHandler.setDefault(new CookieManager());
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8l");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty(
"Cookie",
"BIGipServerPRODCAN-Default=423078080.2087.0000; __utma=44365112.1659763098.1418886605.1427784911.1441869730.4; __utmc=44365112; __utmz=44365112.1427784911.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); JSESSIONID="
+ cookieValue);
responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
File file = new File(prop.getFilePath() + "//XMLs//" + fileName
+ ".xml");
file.delete();
FileWriter fstream = new FileWriter(prop.getFilePath() + "//XMLs//"
+ fileName + ".xml", true);
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null) {
out.write(inputLine.toString());
out.newLine();
response.append(inputLine);
}
in.close();
out.close();`
I am trying to implement the Twitter Search API V1.1
Please correct me if I am wrong.
I performed the below mentioned steps :
Step 1) Created an App in Twitter.
So I got the TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRETCODE.
Step 2) I encoded the concatenation of the above keys separated by ":" with the base UTF-8.
Step3 ) Get the bearer token with the above generated code.
Step4 ) Use the bearer code to get the Tweets on the relevance of a keyword.
I am stuck in Step 3,
where in I am getting the Response as::
Server returned HTTP response code: 400 for URL: https://api.twitter.com/oauth2/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.tcs.crm.socialCRM.action.TwitterIntegration.requestBearerToken(TwitterIntegration.java:74)
at com.tcs.crm.socialCRM.action.TwitterIntegration.getStatusSearch(TwitterIntegration.java:27)
at com.tcs.crm.socialCRM.action.TwitterIntegration.main(TwitterIntegration.java:103)
My code is ::
HttpsURLConnection connection = null;
PrintWriter outWriter = null;
BufferedReader serverResponse = null;
try
{
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Search Tweets");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
connection.setDoOutput( true );
logger.info("Point 1");
//CREATE A WRITER FOR OUTPUT
outWriter = new PrintWriter( connection.getOutputStream() );
logger.info("Point 2");
//SEND PARAMETERS
outWriter.println( "grant_type=client_credentials" );
outWriter.flush();
outWriter.close();
logger.info("Point 3");
//RESPONSE STREAM
serverResponse = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
JSONObject obj = (JSONObject)JSONValue.parse(serverResponse);
logger.info("The return string is "+obj.toString());
return obj.toString();
Please let me know how I can resolve this issue.
I had the same problem with the bearer token from Twitter. Also I test your same code and I received the error 403. After that I was creating my custom method to obtain the bearer token from twitter and I got the solution.
HttpClient httpclient = new DefaultHttpClient();
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
String encodedString = new String(encoded); //converting byte to string
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth2/token");
httppost.setHeader("Authorization","Basic " + encodedString);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
httppost.setEntity(new UrlEncodedFormEntity(parameters));
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
Good luck!
The Twitter dev doc tells to give the "Content-Length":
https://dev.twitter.com/oauth/application-only
(see at "Example Result" below "Step 2: Obtain a bearer token")
However, in my case (with PHP), it works only if I remove "Content-Length".
I know this is rather late, but i found that the following worked for me (thanks #jctd_BDyn for the code to encode the key and secret for basic auth):
private String createBasicAuth() throws UnsupportedEncodingException {
String consumer_key="YOUR_CONSUMER_KEY";
String consumer_secret="YOUR_CONSUMER_SECRET";
// Following the format of the RFC 1738
consumer_key=URLEncoder.encode(consumer_key, "UTF-8");
consumer_secret=URLEncoder.encode(consumer_secret,"UTF-8");
String authorization_header_string=consumer_key+":"+consumer_secret;
byte[] encoded = Base64.encodeBase64(authorization_header_string.getBytes());
return new String(encoded); //converting byte to string
}
private HttpURLConnection createBearerTokenConnection() throws IOException {
URL url = new URL("https://api.twitter.com/oauth2/token");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Authorization", "Basic " + createBasicAuth());
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String formData = "grant_type=client_credentials";
byte[] formDataInBytes = formData.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write(formDataInBytes);
os.close();
log.info("Sending 'POST' request to URL : " + bearerTokenUrl);
return connection;
}
public Optional<BearerToken> getBearerToken() {
try {
HttpURLConnection connection = createBearerTokenConnection();
int responseCode = connection.getResponseCode();
log.info("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
if (responseCode == 200) {
// Transforming from JSON string to POJO
return transformer.toBearerToken(response.toString());
} else {
log.error("Unexpected response code with response " + response.toString());
}
} catch (IOException e) {
log.error(String.format("IO exception on POST to %s", bearerTokenUrl), e);
}
return Optional.empty();
}