I've written a java code to get survey list and then details of those surveys from my account. I am able to get the list of survey IDs but not the details of the survey, using the same API key.
Here's the url constructed:
https://api.surveymonkey.net/v2/surveys/get_survey_details/?api_key=---API-KEY--- --data-binary '{"survey_id":"---SURVEY-ID---"}'
Error:
Server returned HTTP response code: 400 for URL: https://api.surveymonkey.net/v2/surveys/get_survey_details/?api_key=---API-KEY--- --data-binary '{"survey_id":"---SURVEY-ID---"}'
The connection is setup as a post request:
private void resetConnection(String url){
URL ourl;
try {
ourl = new URL(url.toString());
conn = (HttpURLConnection) ourl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + SurveyMonkeyUrl.accessToken);
conn.setRequestProperty("Content-Type", "application/json");
} catch (Exception e) {
e.printStackTrace();
}
}
If I try the URL in the browser it shows:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<h1>Developer Inactive</h1>
Note that the first query is executing fine with the provided same api key and access token.
Related
I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.
The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");
In Jenkins, I am trying to access the change set of a pipeline build by making a HTTP GET call. However I get a 403 error. Please note I am able to access this url in the browser so I know it exists and that the url is working.
The url I am trying to access is the "build url" and then appending "/api/json".
try {
def username = 'username'
def token = 'token'
def apiUrl = 'https://<jenkins-root>/job/<job-name>/<build-number>/api/json'
HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection()
def encoded = Base64.getEncoder().encodeToString((username+":"+token).getBytes("UTF-8"))
connection.setRequestProperty("Authorization", "Bearer " + token)
connection.setRequestProperty("Content-Type", "application/json")
def returnedData = connection.inputStream.text
} catch (Exception ex) {
println ex
}
When running the above code, I am getting the following error.
java.io.IOException: Server returned HTTP response code: 403 for URL: https://my-jenkins-build-url/api/json
Since it's 403 error, I can assume I am authenticated but somehow forbidden to access /api/json of the build? Does anyone have a working way of being able to access /api/json of a jenkins build using http call?
I am working with an API that wants me to send the token along with Header, specifically Content Header.
Here is my code block.
string path_current_user = "me";
var cookie = HttpContext.Request.Cookies.Get("cookietoken");
string cookie_with_token = "ACCESS_TOKEN="+cookie.Value+";";
client.DefaultRequestHeaders.Add("Cookie", cookie_with_token);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
HttpResponseMessage response = await client.GetAsync(path_current_user);
I always get a 410 Unauthorized response. However, during debugging I can collect the values from the client object, and copy paste them into https://www.hurl.it, and I get the expected 200 OK response. So, I know the values that are being stored in the above code are correct. Its not a credentials issue for sure.
I have looked at almost 50 different threads on stack overflow, but none of them talk about this specification situation. Doing a GET with the Header Content set. Here is a screenshot of the HURL that works just fine.
Update 1 - Here is the API documentation for what I am trying to achieve.
Endpoint
GET me
Request Route
GET me
Headers
Content-Type: application/json Cookie: ACCESS_TOKEN="token characters
come here and remove the quotes"; Host: x.x
Update 2 - One of my mentors, recommended the following.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://small-project-api.herokuapp.com/me");
request.Headers.Add.("Content-Type", "application/json");
request.Headers.Add.("Cookie", cookie_with_token);
var response2 = await httpClient.SendAsync(request);
var responsestring = await response2.Content.ReadAsStringAsync();
}
He is of the opinion that may be such a request, as mentioned below, simply won't work in dot net. I am all but ready to give up here.
I tried to send a bearer token to an Auth0 API using Postman and it works perfectly.
I then tried the same using RestSharp (in c#) but it doesn't work at all.
Below is my code. I've tried many different formats but none of them work.. Is there any other way I can try to make it work?
var client = new RestClient("http://domain.auth0.com/api/v2/users");
RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");
//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
ParameterType.HttpHeader);
//request.AddParameter("Authorization",
// String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request);
PS: the token was changed.
The problem is that you're using an HTTP URL. When you issue the first request the token is included, but you receive a redirect response informing that you should be calling the HTTPS endpoint.
Since RestSharp will not include the token in the second request performed automatically due to the first redirect response you get an unauthorized response.
You need to update the URL to be HTTPS which will prevent the redirect and as a consequence solve your problem. If you want to make multiple authenticated request using the same client you also change your code to be:
using RestSharp;
using RestSharp.Authenticators;
class Program
{
static void Main(string[] args)
{
// Use the HTTPS scheme
var client = new RestClient("https://[domain].auth0.com/api/v2/users");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
"eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
"Bearer");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine("{0}", response.StatusCode);
}
}
If you really need to handle redirects and still send the token, check: https://github.com/restsharp/RestSharp/issues/414
Hello trying to capture the actual POST data in an HTTP POST request using browsermob proxy + selenium test framework. So basically i'm running an automated test using selenium and I want to capture the key/value pairs and the actual POST data of a HTTP POST request during the test. Using the following logic I can only capture the key/value pairs of the POST header but not the actual POST data (aka the form field id values). Is there a way to actually capture the POSTDATA (like sniffing applications do such as tamper/live headers in firefox)?
ProxyServer proxyServer = null;
proxyServer = new ProxyServer(9101);
proxyServer.start();
proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);
Proxy proxy = proxyServer.seleniumProxy();
proxy.setHttpProxy("localhost:9101");
//selenium test config code, omitted for brevity
proxyServer.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header[] headers = request.getAllHeaders();
System.out.println("\nRequest Headers\n\n");
for(Header h : headers) {
System.out.println("Key: " + h.getName() + " | Value: " + h.getValue());
}
}
});
An alternate way I read about but could not get to work was to configure the following flags in the browsermob proxy server to true:
proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);
Then output the actual HAR file:
Har har = proxyServer.getHar();
Date date = new Date();
har.writeTo(new File("c:\\tmp\\har_" + date.getTime()));
To see the key/value pairs, POST Data, and actual content of the response... but when I parse the HAR file... I only see the key/value pairs of the POST header again... no POST data... no response content. I am only interested in the actual POST data though.
I also had same problem. As a solution, I captured all the data, converted the HAR file into JSON, and then filtered out only POST requests from the JSON file.