Beanshell code to perform HTTP post request instead of http sampler - post

I'm writing Beanshell code to perform HTTP post request instead of using HTTP sampler
My Code:
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
//Previous Response time
int responseTime = Integer.parseInt(String.valueOf(prev.getTime()));
//Previous Response Size
int size = Integer.parseInt(String.valueOf(prev.getResponseData().length));
//log.info("Reponse time " +responseTime);
//Previous Response Status Code
int responseCode = Integer.parseInt(String.valueOf(prev.getResponseCode()));
String testId =String.valueOf(${__time(yyyyMMdd)});
String executionTimestamp =String.valueOf(${__time(yyyyMMdd)});
//double int executionTimestamp = Integer.parseInt(${__time()});
String Transaction="Transaction_Login";
String applicationName ="Login";
String conversationId ="Sampledata";
String Status="";
String msg="mesages";
//Set Status according to responseCode
if(responseCode=="200"){
Status="OK";
}else {
Status="Fail";
}
HttpClient httpClient = HttpClientBuilder.create().build();
try{
StringEntity params =new StringEntity("\"testId\":\""+testId+"\",\"TransactionName\":\""+Transaction+"\",\"applicationName\":\""+applicationName+"\",\"conversationId\":\""+conversationId+"\",\"size\":\""+size+"\",\"status\":\""+Status+"\",\"messages\":\""+msg+"\",\"executionTimestamp\":\""+executionTimestamp+"\",\"timeTaken\":\""+responseTime+"\"");
HttpPost request = new HttpPost("http://servername/transactionrecorder/");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
log.info("response :" +response);
}catch(Exception e){
log.info("ExceptionKPI :" +e);
}
Error Response:
jmeter.util.BeanShellTestElement: response :HttpResponseProxy{HTTP/1.1 415
[Accept: application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml,
application/x-www-form-urlencoded, application/*+xml, multipart/form-data, application/json;charset=UTF-8, application/*+json;charset=UTF-8, */*, Content-Type: text/html;charset=utf-8, Content-Language: en, Content-Length: 1089, Date: Thu, 28 Sep 2017 09:46:01 GMT] ResponseEntityProxy{[Content-Type: text/html;charset=utf-8,Content-Length: 1089,Chunked: false]}}

You need to send a valid JSON with curly brackets {}, for example:
StringEntity params =new StringEntity("{\"testId\":\""+testId+"\",\"TransactionName\":\""+Transaction+"\",\"applicationName\":\""+applicationName+"\",\"conversationId\":\""+conversationId+"\",\"size\":\""+size+"\",\"status\":\""+Status+"\",\"messages\":\""+msg+"\",\"executionTimestamp\":\""+executionTimestamp+"\",\"timeTaken\":\""+responseTime+"\"}");

Related

how can i convert this Rapid API's HTTP Url to Dart Http request

i have this URL
https://zozor54-whois-lookup-v1.p.rapidapi.com/?rapidapi-key=MYAPIKEYb&domain=DOMAINTOCHECK&format=FORMATTYPE
rapid API gives two header's and other things
I Tried This Code By Exploring HTTP package But Not Working:
import 'package:http/http.dart' as http;
void main() async {
var url = 'https://zozor54-whois-lookup-v1.p.rapidapi.com/?domain=sendrank.com&format=json';
var headers = {
'X-Rapidapi-Key': APIKEyY
'X-Rapidapi-Host': 'zozor54-whois-lookup-v1.p.rapidapi.com',
'Host': 'zozor54-whois-lookup-v1.p.rapidapi.com'
};
var response = await http.get(url, headers: headers);
print(response.body);
}
You need to encode the url with the parameters
final queryParameters = {
'domain': 'sendrank.com',
'format': 'json',
};
final uri = Uri.https('zozor54-whois-lookup-v1.p.rapidapi.com', '/', queryParameters);
final response = await http.get(uri, headers: {
'X-Rapidapi-Key': APIKEyY
'X-Rapidapi-Host': 'zozor54-whois-lookup-v1.p.rapidapi.com',
'Host': 'zozor54-whois-lookup-v1.p.rapidapi.com'
});
See How do you add query parameters to a Dart http request?

Send MultiValueMap as MultiPartFormData in Feign Client

I am trying to convert the below kotlin code from RestTemplate to Feign client. The rest template code sends multiValueMap as request with content-type header multipart/form-data and consumes JSON object as response.
RestTemplate Code:
var headers = HttpHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA
headers.add("custom-header", "value")
val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
body.add("field1", "value1")
body.add("field2", "value2")
val requestEntity = HttpEntity(body, headers)
return restTemplate.postForEntity("https://enmf7tx8y37x.x.pipedream.net/", requestEntity, Object::class.java)
In this case the request is sent as below:
Headers:
Host: enmf7tx8y37x.x.pipedream.net
X-Amzn-Trace-Id: Root=1-6303ecb2-19a833a044ab3bf83f74f256
Content-Length: 342
Accept: application/xml, text/xml, application/json, application/*+xml, application/*+json
Content-Type: multipart/form-data;boundary=_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
custom-header: value
X-B3-TraceId: a67561ec329f9a16
X-B3-SpanId: a6cc94e403bfe318
X-B3-ParentSpanId: a67561ec329f9a16
X-B3-Sampled: 1
User-Agent: Apache-HttpClient/4.5.13 (Java/17.0.3)
Accept-Encoding: gzip,deflate
Body:
--_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
Content-Disposition: form-data; name="field1"
Content-Type: text/plain;charset=UTF-8
Content-Length: 6
value1
--_MtEGFIF4XK_aOU8QsXstQuCliV1-llj
Content-Disposition: form-data; name="field2"
Content-Type: text/plain;charset=UTF-8
Content-Length: 6
value2
--_MtEGFIF4XK_aOU8QsXstQuCliV1-llj--
I tried to do the same in Feign client:
code:
/*val headers = HttpHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA
headers.add("custom-header", "value")*/
val body: MultiValueMap<String, Any> = LinkedMultiValueMap()
body.add("field1", "value1")
body.add("field2", "value2")
val result = testClient.test("value", body)
Feign Client:
#FeignClient(
value = "testClient",
url = "https://enmf7tx8y37x.x.pipedream.net/"
)
interface TestClient {
#PostMapping(
consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
fun test(
#RequestHeader(value = "custom-header") customHeader: String,
#RequestPart("request") request: MultiValueMap<String, Any>
): ResponseEntity<Object>
}
The header are fine but no value present in the body.
Header:
Host: enmf7tx8y37x.x.pipedream.net
X-Amzn-Trace-Id: Root=1-6303ef0f-78c869881a5b27d0707eab9e
Content-Length: 17
Accept: application/json
Authorization: Basic aHlwb2xhYjp0ZXN0c211cmY=
Content-Type: multipart/form-data; charset=UTF-8; boundary=182c75dd399
custom-header: value
X-B3-TraceId: 2989eb4f12e3d417
X-B3-SpanId: 23414bcdf365784c
X-B3-ParentSpanId: 2989eb4f12e3d417
X-B3-Sampled: 1
User-Agent: Java/17.0.3
Body:
--182c75dd399--
I had to add consumes value as multipart/form-data instead of json to get the right header values for Accept and Content-Type.
How can I populate the request using Feign client? If the #RequestPart is String then the value is sent in the body but any other data type like multiValueMap, byteArray, etc were not working
In feign client you cannot use MultiValueMap directly. You have to use MultipartFile datatype for bytearray and for the remaining metadata fields you need to mention each one as a separate argument in the method. Then FeignClient will generate the same request like the one you showed when using RestTemplate.
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestPart
import org.springframework.web.multipart.MultipartFile
#FeignClient(
value = "testClient",
url = "https://enmf7tx8y37x.x.pipedream.net/"
)
interface TestClient {
#PostMapping(
consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
fun test(
#RequestHeader(value = "custom-header") customHeader: String,
#RequestPart(name = "file") file: MultipartFile,
#RequestPart(name = "field1") field1: String
): ResponseEntity<Object>
}
code sample for How to create MultiPartFile:
import org.springframework.mock.web.MockMultipartFile
//val multipartFile: MultipartFile = MockMultipartFile("filename", byteArray)
val multipartFile: MultipartFile = MockMultipartFile("filename", "filename", "content type like application/pdf", byteArray)

MockMVC test throws io.jsonwebtoken.MalformedJwtException when reading JSON

I am using MockMVC to test the JWT Token/authentication and I am having some trouble understanding why the JSON cannot be read.
This is the test that Ive written:
#SpringBootTest
#AutoConfigureMockMvc
public class JwtSecurityTest {
#Autowired
private MockMvc mockMvc;
#Test
public void existentUserCanGetTokenAndAuthentication() throws Exception {
String username = "user";
String password = "pass";
String body = "{"username":"" + username + "","password":"" + password + ""}";
MvcResult result = mockMvc.perform(post("http://localhost:8080/login/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.content(body))
.andDo(MockMvcResultHandlers.print())
.andReturn();
String token = result.getResponse().getContentAsString();
mockMvc.perform(MockMvcRequestBuilders.get("http://localhost:8080/kund")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token))
.andExpect(status().isOk());
}
And the error I get is:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = application/json
Body = {"jwt":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzbHkiLCJleHAiOjE2NTMwODM5NDMsImlhdCI6MTY1MzA0Nzk0M30.V5qqIRzlAtkXEK_OcFbiIlEaOdej3oyGFMy6Aw57ZB8"}
Forwarded URL = null
Redirected URL = null
Cookies = []
io.jsonwebtoken.MalformedJwtException: Unable to read JSON value: ?^?[????M
I find it weird because in the body, we can clearly see that the token looks good.

ModernHttpClient returns Forbidden on Azure Blob upload in Xamarin Android

I'm attempting to update an existing, working Xamarin app to use ModernHttpClient. The app uses Azure REST calls to create containers and upload blobs to Azure Storage.
When I add new NativeMessageHandler() to each new HttpClient() statement to enable ModernHttpClient, the Azure Container continues to get created without any problem, but the call to upload the Blob returns Forbidden.
Here's the code to upload blobs (derived from other's work):
private async Task<bool> PutBlob(String containerName, String blobName, string photoPath)
{
byte[] blobContent = System.IO.File.ReadAllBytes(photoPath);
const String blobType = "BlockBlob";
String requestMethod = "PUT";
Int32 blobLength = blobContent.Length;
String urlPath = String.Format("{0}/{1}", containerName, blobName);
String msVersion = "2009-09-19";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", requestMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = SignThis(stringToSign);
string uri = AzureStorageConstants.BlobEndPoint + urlPath;
HttpClient client = new HttpClient(new NativeMessageHandler());
client.DefaultRequestHeaders.Add("x-ms-blob-type", blobType);
client.DefaultRequestHeaders.Add("x-ms-date", dateInRfc1123Format);
client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
bool isSuccess = false;
var UploadBlobTimer = Insights.TrackTime("UploadBlobTime");
UploadBlobTimer.Start();
using (HttpContent requestContent = new ByteArrayContent(blobContent))
{
HttpResponseMessage response = await client.PutAsync(uri, requestContent);
isSuccess = response.IsSuccessStatusCode;
}
UploadBlobTimer.Stop();
return isSuccess;
}
UPDATE
Below are the Response Headers from a successful .Net and unsuccessful Modern PutBlob call:
.Net
Transfer-Encoding: chunked
ETag: 0x8D280EE1D2ACEFF
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0
x-ms-request-id: 0a35e186-0001-0056-4dd6-b22ebd000000
x-ms-version: 2009-09-19
Date: Tue, 30 Jun 2015 01:49:18 GMT
Modern
Date: Tue, 30 Jun 2015 01:51:22 GMT
OkHttp-Received-Millis: 1435629095708
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1435629083933
Server: Microsoft-HTTPAPI/2.0
x-ms-request-id: c18abaec-0001-0033-09d7-b29fe0000000
Any help is appreciated!

dotnetopenauth twitter api 1.1 signed request

I stuсk on using DNOA library for twitter 1.1 api
enter code here
I am trying to call users/show.json api
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
{
string accessToken = response.AccessToken;
string str2 = response.ExtraData["user_id"];
string userName = response.ExtraData["screen_name"];
Uri location = new Uri("https://api.twitter.com/1.1/users/show.json?user_id=" + str2);
MessageReceivingEndpoint profileEndpoint = new MessageReceivingEndpoint(location, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
HttpWebRequest request = base.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken);
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("accesstoken", accessToken);
try
{
using (WebResponse wresponse = request.GetResponse())
{
var str = Utilities.ProcessResponse(wresponse);
var json = JObject.Parse(str);
dictionary.AddNotEmpty("name", json.Value<string>("name"));
dictionary.AddNotEmpty("location", json.Value<string>("location"));
dictionary.AddNotEmpty("description", json.Value<string>("description"));
dictionary.AddNotEmpty("url", json.Value<string>("url"));
}
}
catch (Exception)
{
}
return new AuthenticationResult(true, base.ProviderName, str2, userName, dictionary);
}
This what is sends to twitter
GET https://api.twitter.com/1.1/users/show.json?user_id=2193937074 HTTP/1.1
Authorization: OAuth oauth_token="2193937074-cgmZbmJIIb75f7MkQgbdjuvQaen2xzM1WFXXC7G",oauth_consumer_key="XVCgN3fkwzTGgeSm1FBa1Q",oauth_nonce="93UjjRkP",oauth_signature_method="HMAC-SHA1",oauth_signature="YzfXzU3VeEI9xl2SfuknPB33%2FiM%3D",oauth_version="1.0",oauth_timestamp="1389265955"
Host: api.twitter.com
The responce is
HTTP/1.1 401 Unauthorized
content-length: 63
content-type: application/json; charset=utf-8
date: Thu, 09 Jan 2014 11:12:36 UTC
server: tfe
set-cookie: guest_id=v1%3A138926595613849064; Domain=.twitter.com; Path=/; Expires=Sat, 09-Jan-2016 11:12:36 UTC
strict-transport-security: max-age=631138519
{"errors":[{"message":"Could not authenticate you","code":32}]}
The dev.twitter's OAuth tool shows the valid sample of signed header:
GET https://api.twitter.com/1.1/users/show.json?user_id=2193937074 HTTP/1.1
Authorization: OAuth oauth_consumer_key="XVCgN3fkwzTGgeSm1FBa1Q", oauth_nonce="dbf6f6c1aa6dc226de25265da3d63167", oauth_signature="K3Qfyc9qANFgckQNyqsaDWCnh%2BY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1389266681", oauth_token="2193937074-cgmZbmJIIb75f7MkQgbdjuvQaen2xzM1WFXXC7G", oauth_version="1.0"
Host: api.twitter.com
It loook's like the main difference is in length of the oauth_nonce?
DNOA - oauth_nonce="93UjjRkP"
OAuth tool - oauth_nonce="dbf6f6c1aa6dc226de25265da3d63167"
I solved the problem.
The main problem is how the signature is created, the TokenSecret is excluded from it's forming. The core of the this behavior is the AuthenticationOnlyCookieOAuthTokenManager manager that is used inside the base DotNetOpenAuth.AspNet.Clients.TwitterClient class.
public class AuthenticationOnlyCookieOAuthTokenManager : IOAuthTokenManager
{
...
public virtual void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret)
{
HttpCookie cookie = new HttpCookie("OAuthTokenSecret") {
Value = string.Empty, //<<< now it's empty
Expires = DateTime.UtcNow.AddDays(-5.0)
};
this.Context.Response.Cookies.Set(cookie);
}
...
}
It's just remove the tokenSecret;
The solution is to use the DotNetOpenAuth.AspNet.Clients.InMemoryOAuthTokenManager class. So you need just derive from OAuthClient and implement proper constructor:
public class TwitterClient : DotNetOpenAuth.AspNet.Clients.OAuthClient
{
protected TwitterClient(string appKey, string appSecret) :
base ("twitter",
new DotNetOpenAuthWebConsumer(
TwitterServiceDescription,
new InMemoryOAuthTokenManager(appKey, appSecret)))
{ }
...
}
Also have found the familiar post Custom OAuth client in MVC4 / DotNetOpenAuth - missing access token secret

Resources