I have this, code which does a post request from an xml (soap) file
public static SoapEnv doRequest(String url, String requestPath) throws IOException, InterruptedException {
String requestBody = inputStreamToString(new FileInputStream(new File(requestPath)));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
XmlMapper xmlMapper = new XmlMapper();
SoapEnv value = xmlMapper.readValue(response.body(), SoapEnv.class);
return value;
}
and it works.
But now I need to add basic authentication. I have login and password.
How can I do this programmatically?
You just need to add a header with the Base64 encoded authentication credentials separated by a colon ":".
Something like this;
String auth = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Basic " + base64Creds)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
Related
I have the sample code snippet. It is returning 400 error. With same BasicAuth creds using OkHttp3 client works well. What is missing here?
```
String BASIC_AUTHORIZAION = "Basic *********"; // masked
String reportRequest = "{***}"; //json string
CloseableHttpClient client = HttpClientBuilder.create().build();
FormBodyPart bodyPart = FormBodyPartBuilder
.create()
.setName("ReportRequest")
.setBody(new StringBody(reportRequest, ContentType.APPLICATION_JSON))
.build();
HttpEntity requestEntity = MultipartEntityBuilder
.create()
.addPart(bodyPart)
.addTextBody("type", ContentType.APPLICATION_JSON.toString())
.build();
HttpUriRequest httpPost = RequestBuilder
.post(MPG_MESSAGE_STATUS_REPORT_URL)
.addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString())
.addHeader("Authorization", BASIC_AUTHORIZAION)
.setEntity(requestEntity)
.build();
HttpResponse response = client.execute(httpPost);
Resolved as it does not need the line to add header for Content-Type MULTIPART_FORM_DATA:
.addHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString())
I'm trying to create a meeting through a web app using a HttpPost request, but I'm getting a 400 BadRequest error with the message "onlinemeeting cannot be null."
HttpPost httpPost = new HttpPost("https://graph.microsoft.com/v1.0/me/onlineMeetings");
LocalDateTime meetingTime = java.time.LocalDateTime.now();
try {
JSONObject bodyJson = new JSONObject();
bodyJson.put("meetingType", "meetNow"); //tried with and without this and still didn't work
bodyJson.put("startDateTime", meetingTime.toString());
bodyJson.put("subject", "TeamsMeeting");
bodyJson.put("participants", new JSONObject().put("organizer",
new JSONObject().put("identity",
new JSONObject().put("user",
new JSONObject().put("id", userId)))));
StringEntity entity = new StringEntity(bodyJson.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
BasicHeader authHeader = new BasicHeader("Authorization", "Bearer " + teamsToken);
httpPost.addHeader(authHeader);
httpPost.addHeader("Content-Type", "application/json");
HttpResponse postResponse = httpClient.execute(httpPost);
String responseContent = EntityUtils.toString(postResponse.getEntity(), StandardCharsets.UTF_8.name());
...
I get this when executing the post request:
{
"error": {
"code":"BadRequest",
"message":"onlinemeeting cannot be null.",
"innerError": {
"date":"2020-07-10T19:09:48",
"request-id":"cfad7871-6595-4efb-a262-13ac42f0e599"
}
}
}
It works when I use postman, but I can't when hitting it through my webapp. Any ideas what might be causing this? Is there something wrong in the Java code? Any help is appreciated.
If you create an online meeting with user token, there is the doc of OnlineMeeting with Java in MS Graph.
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
OnlineMeeting onlineMeeting = new OnlineMeeting();
onlineMeeting.startDateTime = "2019-07-12T21:30:34.2444915+00:00";
onlineMeeting.endDateTime = "2019-07-12T22:00:34.2464912+00:00";
onlineMeeting.subject = "User Token Meeting";
graphClient.me().onlineMeetings()
.buildRequest()
.post(onlineMeeting);
If you create an online meeting with application token, try this code:
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
OnlineMeeting onlineMeeting = new OnlineMeeting();
onlineMeeting.startDateTime = "2019-07-12T21:30:34.2444915+00:00";
onlineMeeting.endDateTime = "2019-07-12T22:00:34.2464912+00:00";
onlineMeeting.subject = "Application Token Meeting";
MeetingParticipants meetingParticipants = new MeetingParticipants();
meetingParticipants.organizer.identity.user.id = "550fae72-d251-43ec-868c-373732c2704f";
onlineMeeting.participants = meetingParticipants;
graphClient.me().onlineMeetings()
.buildRequest()
.post(onlineMeeting);
For more details about the Class OnlineMeeting, see here.
Use Below Code its worked for me:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(authHelper.getMsGraphEndpointHost() + url)
.post(body)
.addHeader("content-type", "application/json")
.addHeader("authorization", accessToken)
.addHeader("cache-control", "no-cache")
.build();
Response responseOk = client.newCall(request).execute();
The issue ended up being with the startDateTime because I think it wasn't in the exact format required. The error message didn't indicate that it was that value, but once removing that from the json body, it worked without having to use the OnlineMeeting object.
I am unable to get MIME for a message using $value like specified in the documentation. How to get MIME?
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + accessToken)
.url("https://graph.microsoft.com/v1.0/me/messages/k4ZDQ5LTgzMTYtNGZhYS04ZTU3LWZhMjFmZmUzNmE1YwBGAAAAAABzUENX1K4kR6h6KAAA7ENoUb5BySZFX6KemUxNwAAAv_a5nAAA=/?value")
.build();
Response response = null;
String body;
try {
response = client.newCall(request).execute();
body = response.body().string();
Your URLs are incorrect, they're using /?value but should be using /$value ($ not ?). The $value is part of the path, not a query param:
https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value
I am trying to send url encoded data using HttpURLConnection method in java. Client shared the below string from Soap UI tester as a sample request:
http://www.clienturl.com/payment?username=bk&password=bk&customerid=100039085&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=2323900&account=00000000&valuedate=2018-07-17&terminal=00010
I've tried all combinations of sending data using java. Am getting response code as 200, but the response is showing that missing mandatory parameters in the request. Please help if there are any error in my code, in writing the request.
StringBuffer response = new StringBuffer();
String EndPointURL = url;
String requestXML = "username=bk&password=bk&customerid=78233209438&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=13903232&account=000000&valuedate=2018-07-17&terminal=00010";
String encodedData = URLEncoder.encode(requestXML, "UTF-8");
System.out.println("Encoded data: " + encodedData);
URL localURL = new URL(EndPointURL);
HttpURLConnection con = (HttpURLConnection) localURL.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept-Charset", charset);
con.setRequestProperty("Content-Length", Integer.toString(encodedData.length()));
OutputStream os = con.getOutputStream();
if you are using Okhttp3, use this code :
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "string-that-you-need-to-pass-in-body");
Request request = new Request.Builder()
.url("url-string")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.build();
Response response = client.newCall(request).execute();
For Unirest :
HttpResponse<String> response = Unirest.post("url-string")
.header("content-type", "application/x-www-form-urlencoded")
.body("string-that-you-need-to-pass-in-body")
.asString();
I have this request for twitter using javax.ws.rs
WebTarget target = new WebTargetBuilder(client, OAUTH_API_ENDPOINT).build();
Builder request = target
.request(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + encodedCredentials)
.header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
Response postResponse = request
.post(Entity.entity("grant_type=client_credentials", MediaType.TEXT_PLAIN));
System.out.println(postResponse.readEntity(String.class));
encodedCredentials are my consumer secret and consumer key encoded in base 64.
The request I'm trying to do is:
POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==Content-Type: application/x-www- form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
I keep getting 403 Forbidden: {"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]}
It seems that the post body isn't set correctly, anyone know how to set it?
What you could try is to change the content type of the POST request body/entity like this:
.post(Entity.entity("grant_type=client_credentials", MediaType.APPLICATION_FORM_URLENCODED)
I have used same in PHP and i think you missed required parameters like oauth_signature
So the final code to obtain the bearer token from Twitter having the consumer key and consumer secret looks like this:
private static final String OAUTH_API_ENDPOINT = "https://api.twitter.com/oauth2/token";
private String consumerKey = "your consumer key";
private String consumerSecret = "your consumer secret";
// Constructs the request for requesting a bearer token and returns that
// token as a string
public String requestBearerToken() throws IOException, InterruptedException, ExecutionException {
String encodedCredentials = encodeCredentials();
Client client = ClientBuilder.newClient();
WebTarget target = new WebTargetBuilder(client, OAUTH_API_ENDPOINT).build();
Response postResponse = target
.request(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + encodedCredentials + "Content-Type: application/x-www-form-urlencoded;charset=UTF-8")
.post(Entity.entity("grant_type=client_credentials", MediaType.APPLICATION_FORM_URLENCODED));
return postResponse.toString();
}
// Encodes the consumer key and secret to create the basic authorization key
public String encodeCredentials() {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
} catch (UnsupportedEncodingException e) {
return new String();
}
}