SharePoint REST API with Java - Authentication error - java

I have the following Java code to send a POST request to SharePoint REST API to create a list and it returns the following authentication errors:
CloseableHttpClient httpClient = null;
try {
String user = xxx;
String password = xxx;
String domain = xxx;
String workstation = "";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
new NTCredentials(user, password, workstation, domain));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
String digestQueryURL = "http://my_sharepoint_site/_api/contextinfo";
HttpPost httpPost = new HttpPost(digestQueryURL);
httpPost.addHeader("Accept", "application/json;odata=verbose");
CloseableHttpResponse response = httpClient.execute(httpPost);
byte[] content = EntityUtils.toByteArray(response.getEntity());
String jsonString = new String(content, "UTF-8");
ObjectMapper mapper = new ObjectMapper();
JsonNode j = mapper.readTree(jsonString);
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
response.close();
// now try to create the list
String url = "http://my_sharepoint_site/_api/web/lists";
HttpPost httpPost2 = new HttpPost(url);
httpPost2.addHeader("X-RequestDigest", getFormDigest(httpClient));
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
String body = "{ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }";
StringEntity se = new StringEntity(body);
httpPost2.setEntity(se);
CloseableHttpResponse response2 = httpClient.execute(httpPost2);
StringBuilder result = new StringBuilder();
System.out.println(response2.getStatusLine().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(response2.getEntity().getContent()));
String output;
while ((output = br.readLine()) != null) {
result.append(output);
}
System.out.println(result.toString());
} catch (Exception e) {
}
Console output
HTTP/1.1 403 FORBIDDEN
{"error":{"code":"-2130575251, System.Runtime.InteropServices.COMException","message":{"lang":"en-US","value":"The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."}}}
I can use very similar code to send GET requests to the REST API to retrieve all lists, retrieve list items, perform all these read operations. However this does not work for POST requests. Am I doing something wrong? The credentials provided are for an account that has full control over the entire site collection, so we can rule out permission errors.

Alright, the problem is really very simple. This line:
String formDigestValue = j.get("d").get("GetContextWebInformation").get("FormDigestValue").toString();
Returns the formDigestValue with quotation marks enclosing it. Using asText() instead of toString() helped.

Related

Microsoft Cognitive Services - Bing Speech to Text with JAVA - curl to http request

i want to code a java http request for posting audio file (wav) for speech to text transformation.
I´m quite new to http requests, and could not find any useful hints how to achieve that.
In https://www.microsoft.com/cognitive-services/en-us/Speech-api/documentation/GetStarted/GetStarted-cURL I was able to get token (Step 1 in url), but now I am struggeling with step 2.
Can someone help or even provide java code for step 2 (post wav file to cognitive services).
CURL Request given:
curl -v -X POST "https://speech.platform.bing.com/recognize? scenarios=smd&appid=D4D52672-91D7-4C74-8AD8- 42B1D98141A5&locale=your_locale&device.os=your_device_os&version=3.0&format=json&instanceid=your_instance_id&requestid=your_request_id" -H 'Authorization: Bearer your_access_token' -H 'Content-type: audio/wav; codec="audio/pcm"; samplerate=16000' --data-binary #your_wave_file
My Java HTTP code so far (Using Apache):
HttpClient client = HttpClientBuilder.create().build();
String url = "https://speech.platform.bing.com/recognize";
String appId = "D4D52672-91D7-4C74-8AD8-42B1D98141A5"; //Always use this. See Docu
String token = "12345"; // received from step 1 (see MS documentation)
String locale = "de-DE";
String deviceOS = "Windows";
String version = "3.0";
String format = "json";
String instanceid = UUID.randomUUID().toString();
String scenarios = "smd";
// setting up post parameters
Map<String, String> postParameters = new HashMap<>();
postParameters.put("scenarios", scenarios);
postParameters.put("appid", appId);
postParameters.put("locale", locale);
postParameters.put("device.os", deviceOS);
postParameters.put("format", format);
postParameters.put("instanceid", instanceid);
postParameters.put("requestid", instanceid);
postParameters.put("version", version);
// setting up HttpPost
HttpPost httpPost = new HttpPost(url);
// PARAMETERS
List<NameValuePair> qparams = new ArrayList<>();
for (Map.Entry<String, String> s : postParameters.entrySet()) {
qparams.add(new BasicNameValuePair(s.getKey(), s.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(qparams));
// HEADERS
String wavFile = "C:\\Folder\\AudioData.wav";
Map<String, String> postHeaders = new HashMap<>();
postHeaders.put("Authorization", "Bearer " + token);
postHeaders.put("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
for (Map.Entry<String, String> entry : postHeaders.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
// WAV FILE
File file = new File(wavFile);
FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("bin", bin);
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
// RESPONSE
HttpResponse response = client.execute(httpPost);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
My Response code is 200, but my response.getEntity().getContent() is empty. I expect a JSON there.
btw: if i fire this up with curl (with set parameters of course) it works, and I get a JSON back with recognized speech to text.
Can you help me with that?
Nycon

HTTP/1.1 400 Bad Request in java HTTP post

I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out ....
Here is my sample code:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. You are using colon (:) to separate keys from their values, but instead, the equal sign (=) must be used:
Wrong: "importFormatCode:1&data:" + params
Correct: "importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded)
Apart from that, you must not URL-encode the entire string but only the keys and the values. Otherwise you'll also encode the separator characters = and &!
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils (assuming that you're using Apache HTTP Components):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code

Corrupted Json in Android Eclipse

im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}

Json from C# to JAVA

I have a web application in C#, and I use JsonSerializer to create a json.
Now I'm wotrking on an android application and I'm trying to read the json.
On my Android application, my code is
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "application/json; charset=utf-8");
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page); // here it explodes
}
It get explodes when trying to create a json object, because the value of "page" is
"{\\"Key\\":\\"1\\",\\"RowVersion\\":[0,0,0,0,0,0,226,148].....
When I try to get the json on the browser manually (with direct GET url), I get
"{\"Key\":\"1\",\"RowVersion\":[0,0,0,0,0,0,226,148]......
When I copy this string manually it works fine.
How can I fix it?
You are returned a JSON object as a String whereas you expected a JSON object...
With Jackson, this is easily solved:
final ObjectMapper mapper = new ObjectMapper();
// JSON object as a string...
final JsonNode malformed = mapper.readTree(response.getEntity().getContent());
// To JSON object
final JsonNode OK = mapper.readTree(malformed.textValue());
Either this, or fix the server side so as to return the JSON object!
I think that your code it too complicated, try do it like this:
String page = EntityUtils.toString(response.getEntity());

Android Java strange issue building URL

So I'm building an URL to be called to get a JSON response but facing a strange issue. Building the URL as shown below returns "Not found" but for testing purposes I just built the URL as such "http://api.themoviedb.org/3/search/person?api_key=XXX&query=brad" and didn't append anything and that returned the correct response. Also tried not encoding "text" and same thing...Not found. Any ideas?
StringBuilder url = new StringBuilder();
url.append("http://api.themoviedb.org/3/search/person?api_key=XXX&query=").append(URLEncoder.encode(text, ENCODING));
Log.v("URL", url.toString());
try {
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream input = bufHttpEntity.getContent();
String result = toString(input);
//JSONObject json = new JSONObject(result);
return result;
Try using the code I have below. I've copied and pasted it out of some code I use and I know it works. May not solve your problem but I think its worth a shot. I've edited it a little bit and it should just be copy and paste into your code now.
HttpGet request = new HttpGet(new URI(url.toString()));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONObject jResponse = new JSONObject(builder.toString());

Categories

Resources