From my GAE server side code, Iam using urlfetchservice to update the datastore on another GAE. This results in Response code 302
Please find the code snippet below,
String urlVal = "https://valeo-is-qc-dev.appspot.com/a/qccards/"+modelObj.getQc_reference_id()+"/updatellcreference?llcref="+modelObj.getReference()+"&llcrefid="+modelObj.getId();
URL url = new URL(urlVal);
// Create HTTPRequest and set headers
com.google.appengine.api.urlfetch.FetchOptions fetchOptions = com.google.appengine.api.urlfetch.FetchOptions.Builder.withDefaults();
fetchOptions.doNotValidateCertificate();
fetchOptions.doNotFollowRedirects();
HTTPRequest httpRequest = null;
httpRequest = new HTTPRequest(new URL(url.toString()), HTTPMethod.PUT,fetchOptions);
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + token_id));
httpRequest.addHeader(new HTTPHeader("X-Appengine-Inbound-Appid", "valeo-is-llc-dev"));
httpRequest.addHeader(new HTTPHeader("Host", "https://test-is-abc-dev.appspot.com"));
httpRequest.addHeader(new HTTPHeader("Content-Type", "text/plain"));
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
HTTPResponse httpResponse = null;
httpResponse = fetcher.fetch(httpRequest);
if (httpResponse.getResponseCode() == HttpURLConnection.HTTP_OK) {
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.getResponseCode());
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.toString());
} else {
// Server returned HTTP error code.
LOGGER.log(Level.INFO, "abc def Bridge Response FAIL --- " + httpResponse.getResponseCode());
}
Related
I have a rest post call. whenever I try to hit using postman it is working fine. but If I try same post call using JerseyAPI Client. I'm getting 400 Bad request
String URI = "rest uri";
Client client = Client.create();
WebResource webResource = client.resource(URI);
try {
String input1 = "{\"callType\": \"UPDATE\",\"emails\": [\"qa_tester2222#gmail.com\",\"qa_tester2222#gmail.com\"],\"event\": \"UPDATE_EVENT\",\"externalIds\": [ \"id\" ], \"fraudAction\": \"CONFIRMED_FRAUD\",\"fraudCategory\": \"Account Takeover\",\"memo\": \"test fraud case management for AD\",\"origin\": \"SE4\",\"phones\": [],\"requester\": \"corsairUser\",\"source\": \"LIVE\" }";
ClientResponse response = webResource.type("application/json")
.header("Authorization", "Basic secretKey")
.post(ClientResponse.class, input1);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (
Exception e) {
e.printStackTrace();
}
}
If I run same request in Postman using a above input, I'm able to hit api successfully and get 200, but getting 400 in JerseyAPI
Since you are getting a Bad Request response, I think you should create your JSON string using a proper JSON tool. You can start by creating a JSON object from your string and then use the JSON object to retrieve the input.
Creating the JSON object:
JSONObject jsonObject = new JSONObject(string);
Using the JSON object as your input:
ClientResponse response = webResource.type("application/json")
.header("Authorization", "Basic secretKey")
.post(ClientResponse.class, jsonObject.toString());
I have a requirement to call a controller from java code itself. The controller is as follows,
#RequestMapping(value = "temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
I am trying to call the above controller using http post as follows,
String url ="http://localhost:8081/LeadM" + "/temp/?searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
InputStream rstream = entity.getContent();
jsonObject = new JSONObject(new JSONTokener(rstream));
where reqParam is a class object is the class object and colMapObj is the map that I want to pass to the above controller. However when http post is executed it gives exception in the url.
If anybody knows the right way then please suggest, thank you.
This should work
#RequestMapping(value = "/temp", method = RequestMethod.POST)
#ResponseBody
public String uploadDataFromExcel(#RequestBody Map<String, String> colMapObj, #ModelAttribute ReqParam reqParam) {
}
and url should be
String url ="http://localhost:8081/LeadM" + "/temp?"+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
URL dos not work with spaces.From your code above: " &exportDiscardRec="
To avoid such issues use URIBuilder or something similar if possible.
Now for the request, you are not building your request correctly for example you do not provide the body.
Check below example:
Map<String, String> colMapObj = new HashMap<>();
colMapObj.put("testKey", "testdata");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject body = new JSONObject(colMapObj);
StringEntity entity = new StringEntity(body.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getEntity().toString());
client.close();
More examples just google "apache http client post examples" (e.g. http://www.baeldung.com/httpclient-post-http-request)
Encode your query string.
String endpoint = "http://localhost:8081/LeadM/tmp?";
String query = "searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
String q = URLEncoder.encode(query, "UTF-8");
String finalUrl = endpoint + q;
If this doesn't work, then encode individual params before concatenating.
On a side note
if you r running in same jvm then you can call method directly
if you own the the upload method then consider changing query string into form param
I'm writing a simple android app in Java and recently implemented retrieving a token for a user from Microsoft Dynamics CRM (I have created a connected app in Azure, got application id, secret etc).
I want other users of this application to be able to connect to their CRMs and organizations.
Now I'm trying to use the token with the REST API and getting 401 error.
Read all the related answers here, nothing helped. The code I'm using:
//retrieved the authorization code by this url:
mAuthorizationUrl = Configuration.AUTHORIZE_ENDPOINT + "?response_type=code&client_id="
+ Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI;
...
//Retrieving access_token:
String body_content = "grant_type=authorization_code&client_id=" +
Configuration.CLIENT_ID + "&redirect_uri=" + Configuration.REDIRECT_URI
+ "&code=" + code + "&resource=" + Configuration.CLIENT_ID;
//I don't have app URI (resource) in Azure, so I used app id (client id).
//This worked (see above).
RequestBody body = RequestBody.create(
MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),
body_content);
Request request = new Request.Builder()
.url(Configuration.TOKEN_RETRIEVAL_ENDPOINT)
.post(body)
.build();
Response response = new OkHttpClient().newCall(request).execute();
String responseString = response.body().string();
JSONObject json = new JSONObject(responseString);
String token = json.getString("access_token");
//NOT WORKING CODE:
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
Map<String, String> headers = new ArrayMap<>();
headers.put("Authorization", "Bearer " + token));
headers.put("Accept", "application/json");
request = new Request.Builder()
.url(Configuration.REST_ENDPOINT)
.headers(Headers.of(headers))
.build();
try {
response = okHttpClient
.newCall(request)
.execute();
statusCode = response.code();
}
...
//401 UNAUTHORIZED
Endpoints I used:
AUTHORIZE_ENDPOINT = https://login.microsoftonline.com/common/oauth2/authorize
TOKEN_RETRIEVAL_ENDPOINT = https://login.microsoftonline.com/common/oauth2/token
REST_ENDPOINT = url_to_crm/api/data/v9.0/
Here are two sample Java projects that connect and authenticate with the Dynamics Web API via Azure:
Link 1
Link 2
Hope this helps.
I am looking to interact with a Documentum Repository using their REST API. I would like to use the http-client 4.3 jars to perform this interaction.
I was hoping someone might have a sample that would help point me in the correct direction on how to interact with DCTM.
I am having trouble finding a clear and simple example of how to do this.
Thanks
I know it is a bit late to answer this question. But i want to answer to help those who still need a code for making requests to the rest api. Here is a full example of sending a post request to the rest api for starting a workflow.
For other needs you can check the Document called Documentum xCP Rest Services provided by EMC : https://support.emc.com/docu52500_Documentum-xCP-REST-Services-2.1-Development-Guide.pdf?language=en_US&request=akamai and compare with this example, change it according to it's needs.
UPDATE:
Also if you are not using xcp here is the Documentation for rest api without it emc.com/collateral/TechnicalDocument/docu57895.pdf
You can also check my answer here How can I use REST to copy an object in Documentum 7.x for geting object data and content from the rest api ( without xcp )
String strResponse = "";
String process_id = "system_name of the process you want to start";
String url = "Your App Url Here/processes/" + process_id;
String json = "{"+
"\"run-stateless\" : \"false\","+
"\"data\" :"+
" { "+
" \"variables\" : "+
" { \"Variable name\" : \"Variable value\" } "+
" } "+
"}";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
BufferedReader rd = null;
CloseableHttpResponse cls = null;
try {
HttpPost request = new HttpPost(url);
// set timeouts as you like
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(60 * 1000).setConnectTimeout(20 * 1000)
.setConnectionRequestTimeout(20 * 1000).build();
request.setConfig(config);
StringEntity params = new StringEntity(json);
request.addHeader("Accept", "application/json");
request.addHeader(
"Authorization",
"Basic "
+ com.documentum.xmlconfig.util.Base64
.encode("username here" + ":"
+ "password here"));
request.addHeader("Content-Type", "application/vnd.emc.xcp+json");
request.setEntity(params);
try {
cls = httpClient.execute(request);
HttpEntity entity = cls.getEntity();
rd = new BufferedReader(new InputStreamReader(
entity.getContent()));
String line = "";
while (line != null) {
line = rd.readLine();
strResponse += line;
}
strResponse = strResponse.trim().replace("\n", "");
String statusline = cls.getStatusLine().toString();
if (!statusline.contains("200") && !statusline.contains("201")) {
Log.write("Process is not started");
// log the strResponse or do something with it
} else {
System.out.println("Process started successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
} finally {
// using commons-io-2.4.jar
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(cls);
IOUtils.closeQuietly(rd);
}
I have restlet sample client program which sends the digest request. Similar to this I need java client program which sends a digest request using HttpClient api.
Can anybody send me sample code. Thanks in advance.
Reference reference = new Reference("http://localhost:8092/authenticate");
Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.GET, reference);
Response response = client.handle(request);
System.out.println("response: "+response.getStatus());
Form form = new Form();
form.add("username", "rajesh");
form.add("uri", reference.getPath());
// Loop over the challengeRequest objects sent by the server.
for (ChallengeRequest challengeRequest : response
.getChallengeRequests()) {
// Get the data from the server's response.
if (ChallengeScheme.HTTP_DIGEST
.equals(challengeRequest.getScheme())) {
Series<Parameter> params = challengeRequest.getParameters();
form.add(params.getFirst("nonce"));
form.add(params.getFirst("realm"));
form.add(params.getFirst("domain"));
form.add(params.getFirst("algorithm"));
form.add(params.getFirst("qop"));
}
}
// Compute the required data
String a1 = Engine.getInstance().toMd5(
"rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh");
String a2 = Engine.getInstance().toMd5(
request.getMethod() + ":" + form.getFirstValue("uri"));
form.add("response", Engine.getInstance().toMd5(
a1 + ":" + form.getFirstValue("nonce") + ":" + a2));
ChallengeResponse challengeResponse = new ChallengeResponse(
ChallengeScheme.HTTP_DIGEST, "", "");
challengeResponse.setCredentialComponents(form);
// Send the completed request
request.setChallengeResponse(challengeResponse);
response = client.handle(request);
// Should be 200.
System.out.println(response.getStatus());
Have you tried the following:
ChallengeResponse challengeResponse = new ChallengeResponse(challengeRequest, "rajesh", <password>);
Here you go:
HttpClient client = new HttpClient();
Credentials creds = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(new AuthScope(host, port, realmName), creds);
GetMethod get = new GetMethod(url);
get.setDoAuthentication(true);
client.getParams().setAuthenticationPreemptive(true); // seems to be necessary in most cases
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));//need to register DIGEST scheme not the basic
client.getAuthSchemes().register(AuthPolicy.DIGEST, new DigestSchemeFactory());
client.executeMethod(get);
result = get.getResponseBodyAsString();