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();
Related
I'm trying to send a post request like get request, but I I'm getting server error 500, although I'm sure it works correctly.
Tell me how to send a post request with parameters via formdata?
My GET request:
url = 'http://logicased-mog.service.btlab.ru/alfresco/s/lecm/repository/api/getUploaderFolders?rootNode=alfresco://user/temp&generateDirectories=false'
def baseUrl = new URL(url)
HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
def authorization = 'user1:user1'
encodedBytes = new String(Base64.getEncoder().encode(authorization.getBytes()))
authorization = "Basic " + new String(encodedBytes);
connection.setRequestProperty("Authorization", authorization);
connection.addRequestProperty("Accept", "application/json")
connection.with {
doOutput = true
requestMethod = 'GET'
resp = content.text
}
connection.disconnect()
My POST request (doesn't work, error 500 is returned)
baseUrl = 'http://logicased-mog.service.btlab.ru/alfresco/s/api/upload?Alfresco-CSRFToken=null'
def data = [:]
def createUrl = new URL('http://logicased-mog.service.btlab.ru/alfresco/s/mog/outgoing/createOutgoing')
connection = (HttpURLConnection) createUrl.openConnection();
connection.setRequestProperty("Authorization", authorization);
connection.addRequestProperty("Accept", "application/json")
connection.with {
doOutput = true
requestMethod = 'POST'
nodeRef = resp
fromSoo = 1
attachments = []
responseTo = resp
signer = 'markinaaa'
resp = content.text }
params nodeRef,fromSoo, attachments, responseTo and signer I want to pass in the request body
Thanks!
Try by adding the content header like:
connection.addRequestProperty("Content-Type", "application/json") ( or plan/text as with ur data type)
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 make a post request using okHttp with the next code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
The server response with:
response
{
message: {
user: {
id: 12,
name: 'myName'
},
message: 'Usuario creado con éxito.',
code: 200
}
}
But the response that okHttp gives me is:
Response{protocol=http/1.1, code=200, message=OK, url=http://localhost:2222/api/users}
There isn´t a way to get what the server sends me with okHttp?
If the response is sent in the body you can get it with:
response.body().string();
You just had to look on the documentation
¡Salud!
What you are getting is the header of response object. you can access the body of response by:
response.body().string();
full code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
String responseBody = response.body().string();
Can't really find any help on this but I've been trying to send a post request with HtmlUnit. The code I have is:
final WebClient webClient = new WebClient();
// Instead of requesting the page directly we create a WebRequestSettings object
WebRequest requestSettings = new WebRequest(
new URL("www.URLHERE.com"), HttpMethod.POST);
// Then we set the request parameters
requestSettings.setRequestParameters(new ArrayList());
requestSettings.getRequestParameters().add(new NameValuePair("name", "value"));
// Finally, we can get the page
HtmlPage page = webClient.getPage(requestSettings);
Is there an easier way I could carry out a POST request?
This is how it's done
public void post() throws Exception
{
URL url = new URL("YOURURL");
WebRequest requestSettings = new WebRequest(url, HttpMethod.POST);
requestSettings.setAdditionalHeader("Accept", "*/*");
requestSettings.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
requestSettings.setAdditionalHeader("Referer", "REFURLHERE");
requestSettings.setAdditionalHeader("Accept-Language", "en-US,en;q=0.8");
requestSettings.setAdditionalHeader("Accept-Encoding", "gzip,deflate,sdch");
requestSettings.setAdditionalHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
requestSettings.setAdditionalHeader("X-Requested-With", "XMLHttpRequest");
requestSettings.setAdditionalHeader("Cache-Control", "no-cache");
requestSettings.setAdditionalHeader("Pragma", "no-cache");
requestSettings.setAdditionalHeader("Origin", "https://YOURHOST");
requestSettings.setRequestBody("REQUESTBODY");
Page redirectPage = webClient.getPage(requestSettings);
}
You can customize it however you want. Add/remove headers, add/remove request body, etc ...
There are n numbers of possible libraries using which you can call rest web services.
1) Apache Http client
2) Retrofit from Square
3) Volley from google
I have used Http Apache client and Retrofit both. Both are awesome.
Here is code example of Apache HTTP client to send Post request
String token = null;
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(LOGIN_URL);
StringBuilder sb = new StringBuilder();
sb.append("{\"userName\":\"").append(user).append("\",").append("\"password\":\"").append(password).append("\"}");
String content = sb.toString();
StringEntity input = new StringEntity(content);
input.setContentType("application/json");
postRequest.setHeader("Content-Type", "application/json");
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201)
{
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
Header[] headers = response.getHeaders("X-Auth-Token");
if (headers != null && headers.length > 0)
{
token = headers[0].getValue();
}
return token;