goal : I'm using sharepoint REST APIs to create a list in my sharepoint site. In this case I'm using okHttp as my Http library.
expected result : should return 201 as response code when calling the request using okHttp.
actual result :
Exception in thread "main" java.io.IOException: unexpected code Response{protocol=http/1.1, code=400, message=Bad Request, url=https://***.sharepoint.com/_api/web/lists}
at com.**.list.ListImpl.createAList(ListImpl.java:39)
at com.**.Test.main(Test.java:16)
following are the steps I have implemented:
I have used the postman to test the API. It worked fine , got the desired result.
I have debugged the code, expected values were successfully assigned to the respective variables as well.
I know that 400 bad request means , there is something wrong with JSON data and server couldn't parse the json which I'm sending. Eventhough I tried , but couldn't find the way to resolve this. Any help would be appreciated.
following are the code samples.
ListImple.java
package com.****.list;
import com.**.app.properties.ApplicationProperties;
import com.**.metadata.MetaData;
import com.**.rest.TokenService;
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
public class ListImpl implements List {
private String api ="/lists";
private MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
@Override
public void createAList(String token) throws IOException {
MetaData metaData = new MetaData("SP.List");
ListModel listData = new ListModel(metaData,true,104,
true,"sample description 02", "list-number-02");
JSONObject jsonObject = new JSONObject(listData);
String data = jsonObject.toString();
RequestBody formBody = RequestBody.create(data, JSON);
System.out.println(formBody.contentType());
Request request = new Request.Builder()
.url(ApplicationProperties.getBaseUrl() + api)
.addHeader("Authorization", "Bearer " + token)
.addHeader("Content-Type", "application/json;odata=verbose")
.addHeader("accept", "application/json;odata=verbose")
.addHeader("X-RequestDigest", "0x87D8893C3016E8E7EB288E13276DE7C8D5250EC26025FDADCF9A3E6C86DF0C4A5EC86B3B4AEAD882E06058BC0919A61E10C3DEFDE3B275E67698A9E1B4456CEF")
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
if(!response.isSuccessful()) {
throw new IOException("unexpected code " + response);
}
System.out.println(response.body().string());
}
}
}
After days of debugging I came to conclusion that problem was OkHttp rest library.
So I removed that library and included the org.apache.httpcomponents
artifact in the pom.xml file.
now All are working fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With