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)
Related
I'm trying to communicate with external api. The API endpoint uses POST method. It uses Form-data to post. I did the implementation of sending the data using MultipartFormDataContent. However, it seems the server is not recognizing any parameter I send. My code is below, I have searched and tried many ways but still got no correct response from the server.
Parameter name: pParty_id
Note: the server respond correctly through PostMan.
public async Task<JsonResult> PostFormAsync<U>(string method, string endpoint, IFormFile file, string pParty_id)
{
HttpClient _client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
MultipartFormDataContent multipart = new MultipartFormDataContent
{
{new StringContent(pParty_id),"pParty_id"}
};
//foreach (var header in headers)
// _client.DefaultRequestHeaders.Add(header.Key, header.Value);
_client.DefaultRequestHeaders.Add("Connection", "keep-alive");
_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
_client.DefaultRequestHeaders.Add("Accept", "*/*");
_client.DefaultRequestHeaders.Add("User-Agent", "C# app");
//_client.DefaultRequestHeaders.Add("Content-Type", "multipart/form-data");
var fileContent = new StreamContent(file.OpenReadStream())
{
Headers = {
ContentLength = file.Length,
ContentType = new MediaTypeHeaderValue(file.ContentType)
}
};
string boundary = Guid.NewGuid().ToString();
multipart.Headers.Remove("Content-Type");
multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
var body = new StringContent(pParty_id);
multipart.Add(body, "pParty_id");
body.Headers.ContentDisposition = new ContentDispositionHeaderValue("pParty_id");
switch (method)
{
case "POST":
response = await _client.PostAsync(
endpoint, multipart);
break;
}
var responseString = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
_client.Dispose();
return new JsonResult(JsonConvert.DeserializeObject<U>(responseString))
{ StatusCode = (int) response.StatusCode };
}
I'm using client credential secret to run API on Microsoft Endpoint (Intune).
Example used from link.
Getting access token. (Working)
Get android Managed App Protections. (Working using GET HTTP Method)
Patch Request. (Not Working)
The examples do not mention any PATCH or POST request, hence need some help for it.
I tried the below code snippet but it fails.
private void setAndroidModels(final String accessToken, final String policyId, final String modelList)
throws IOException {
URL url = new URL(
"https://graph.microsoft.com/beta/deviceAppManagement/androidManagedAppProtections/" + policyId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PATCH");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = modelList.getBytes();
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
System.out.println("POST Response Code : " + httpResponseCode);
System.out.println("POST Response Message : " + conn.getResponseMessage());
}
Result : Exception in thread "main" java.net.ProtocolException: Invalid HTTP method: PATCH
Also tried
private void setAndroidModels(final String accessToken, final String policyId, final String modelList)
throws IOException {
URL url = new URL(
"https://graph.microsoft.com/beta/deviceAppManagement/androidManagedAppProtections/" + policyId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = modelList.getBytes();
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
System.out.println("POST Response Code : " + httpResponseCode);
System.out.println("POST Response Message : " + conn.getResponseMessage());
}
Result :
POST Response Code : 400
POST Response Message: Bad Request
How can I get the client credential secret logic working for POST and PATCH HTTP Methods?
We can directly call patch request in MS Graph.
When creating PATCH requests to the API, you need to create a new
PATCH object that contains only the information you want to update.
This should be distinct from any objects you receive from the service
from a GET or a POST.
Please refer Document for more details.
For example, Patch rquest to user
User realMe = graphClient.me().buildRequest().get();
User patchMe = new User();
patchMe.givenName = "Beth";
realMe = graphClient
.users(realMe.userPrincipalName)
.buildRequest()
.patch(patchMe);
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();
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;
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();
}
}