I've been using CURL and php to send the following:
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => count($postfields),
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_VERBOSE => true,
CURLOPT_SSLCERT => 'C:\mycert.pem',
CURLOPT_SSLCERTPASSWD => 'mypass',
CURLOPT_SSLCERTTYPE => 'PEM'
));
I've not included the postfields to keep it brief.
This works very well. However after much googling I can't find a simple way to do this using HTTPClient. I just want to include a certificate with the POST.
TIA
You need to create a trust store containing your certificate.
My blog post at http://blog.chariotsolutions.com/2013/01/https-with-client-certificates-on.html contains a little more than you need (it includes supporting self-signed client and server certs), but should give you everything you need.
Related
I need to send string data to an external url which is an API for clients, but I always get the server sending back an error, and then I checked the log in the server which is written in JAVA, it throws an exception
"java.lang.NumberFormatException: For input string: "{"success":false,"errorCode":"500","message":"Unknown Error!","value":null,"totalPageCount":0,"footerValue":null}"
and here's my piece of php code:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $params
),
));
$received = file_get_contents(URL, false, $context);
echo $received.'<br>';
I'm pretty sure the data I send to the server is in correct format as I have the access to the log, and I know that all response parameters from the server are in JSON, UTF-8 and post method, is there something I missed?
If more information needed please let me know, thanks.
You need to parse the string. You are getting NumberFormatException and this is because your server is receiving data which is not a numeric.
Integer.parseInt() // in java
You can parse the content in server side this way or send numeric data.
Another method:
Integer.valueOf() // in java
Is there any REST API from BitBucket, which can be called from a GoLang so that it will create a new REPOSITORY. I can fetch the details of existing but not able to create a new one. Remember CURL is not requirement. Kindly help, stuck from some time into it. Is there any way do it via JAVA as well? If Java can do, then I think GoLang should be able to. Suggest!
Looking through their documentation I found this endpoint which allows you to create repos using their API.
Calling a REST API endpoint can be done from any language.
Here is a nice tutorial where it explains how you can call json API endpoints using GO.
Thanks for Help guys!
Yes, I am able to resolve this issue,with a colleague pointing out the mistake.
Things required:
1. You should be having complete access for the bitBucket.
2. You should have correct URL where to connect with for the REST API. Note: REST API url is different than that of direct URL and get the versions Correct.
Go Code for same is::
import (
"encoding/json"
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url:=fmt.Sprintf("https://<Server BitBucket>/rest/api/1.0/projects/<PROJECT WHERE REPO TO BE CREATED>/repos");
jsonData := map[string]string{"name":"<REPONAME>","scmID":"git","forkable":"true"}
jsonValue,_:=json.Marshal(jsonData)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth("<USERNAME>", "<PASSWORD>")
fmt.Println("++",req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
This will give the response as 201 and yes, it will be created!!
i build a web service project by wash_out gem ,i can call functions use the Savon gem ,but when i tried to connect to my webservice server by soap.jar in java; its doesn't work , how to write the url of functions? and how to send actions by get(default is post ,so rails will throw the routing error,because wash_out generate wsdl routes in GET way);
here is my code
class HxppController < ApplicationController
soap_service namespace: 'urn:WashOut'
soap_action "CreateOrUpdateDictionary",
:args => {ZTYPE: :string, ZCODE: :string, ZDESC: :string },
:return => {:ZRTN_CODE => :string, ZRTN_RESULT: :string}
def CreateOrUpdateDictionary
render :soap => {:ZRTN_CODE => "S", ZRTN_RESULT: "success"}
end
end
My webservice url is localhost:3000/hxpp/wsdl ;
how to fix this? thanks a lot
I'm migrating a project from PHP to Java.
I had no problem doing this, but the project contains a HTTP request which I couldn't set up yet. It has to grab a JSON from an API (Authorisation required) and then save it as a variable (which gets passed on to my parser class).
This is the code I've used in php:
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/json' . "\r\n"
. 'Authorization: Bearer ' . $token . "\r\n",
),
)));
$url is the request url and $token the authorisation for the API.
I've already tried a couple of solutions and libraries from StackOverflow, but couldn't get any of these to work in the Java Version. Also I haven't found code which includes the response code, which would actually allow the program to notify the user what went wrong.
Update: I've tried to use the libery linked in the comments, but encoding the url just doesn't work, I get a java.io.UnsupportedEncodingException:
String url = URLEncoder.encode(requestURL,"UTF-8");
I also tried:
Url url = URLEncoder.encode(requestURL,"UTF-8");
which resulted in the same error.
Documentation doesn't help to fix this. Can someone explain what I'm doing wrong or give me some example code?
I have to verify the request call from a server which is OAuth signed. This request call is made to my server, and i need to verify that request is made from that server. I have the oauth consumer key and consumer secret. I have been looking into signpost and jersey library APIs for signature verification. They have not been of much help.
The call is made from a particular server(with two-legged OAuth 1.0) to my servlet. Please suggest a simpler library or example to do the OAuth verification.
I faced the same issue when coding a web service using the Play framework in Scala which I had to code using Java libraries in order to solve it so even though my code snippet is in Scala, I think that it can help. This answer may be coming a bit late but hopefully somebody might find it useful.
In my case, an external service is calling my REST endpoint while providing different oauth parameters inside the Authorization header. In order to validate the oauth_signature provided as part of these parameters, I had to extract the nonce and the timestamp parameter from the header and calculate a signature based on them plus based on a few other parameters including my oauth key and secret, and the original request uri.
This code is in scala but I think that you can infer what to do from it. It is also using the java OAuthSignatureCalculator so it may even be easier to code directly in Java.
private def getProtocolFromRequest[T](request: Request[T]): String = {
// To handle the case where a SSL offloading is involved
request.headers.get(HeaderNames.X_FORWARDED_PROTO) match {
case Some(forwardedProto: String) => forwardedProto
case _ => if(request.secure) "https" else "http"
}
}
def isOAuthSignatureValid[T](request: Request[T]): Boolean = {
request.headers.get(com.ning.http.client.oauth.OAuthSignatureCalculator.HEADER_AUTHORIZATION) match {
case Some(authorizationHeaders) =>
val AuthRegex = ".*oauth_nonce=\"([^\"]*)\".*oauth_signature=\"([^\"]*)\".*oauth_timestamp=\"([^\"]*)\".*".r
authorizationHeaders match {
case AuthRegex(nonce: String, providedSignature: String, timestamp: String) =>
val signatureCalculator = new OAuthSignatureCalculator(new com.ning.http.client.oauth.ConsumerKey(oauthKey, oauthSecret), new com.ning.http.client.oauth.RequestToken(null, ""))
val params = request.queryString.map(query => new Param(query._1, query._2.head)).toSeq
val protocol = getProtocolFromRequest(request)
val url = s"$protocol://${request.host}${request.path}"
val expectedSignature = signatureCalculator.calculateSignature(
request.method,
Uri.create(url),
timestamp.toInt,
nonce,
new util.ArrayList(),
scala.collection.JavaConversions.seqAsJavaList(params)
)
expectedSignature.equals(URLDecoder.decode(providedSignature, "UTF-8"))
case _ => false
}
case _ => false
}
}
The flow is the following:
Grab the Authorization header
Create a OAuthSignatureCalculator by providing your oauth consumer key and secret. In my case I am not using any request token.
Extract the needed oauth parameters from the authorization headers: signature, nonce, timestamp
Use the OAuthSignatureCalculator to calculate a signature
Compare the provided signature with the calculated one. If they match, the caller is authentified, otherwise, it's not.
Hopefully that can help somebody