I couldn't find a way to authenticate my app with my server using the Bearer token I had created. it works perfectly with Postman though.
I've tried using UTF-8 encoding, using ?access_token in url, tried a lot of answers I found on Stackoverflow.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzda2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer eyJ0NiJ9.eyJpc3MiOiJmOWVkZDI5YjY2MTE0Mjc3YNDdmMzIwMWI2ZCIsImlhdCI6MTU1OTIwMjYwOCwiZXhwIjoxODc0NTYyNjA4fQ.HEb3b6kpW6OzAxcLumS8DlJWmZVAWfn0Lg84seBZGpQ"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("entity_id", "script.gt11"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
The error I get is 401 Unauthorized on every attempt.
I'm using Volley, but when I set up the headers, I do it with this:
HashMap<String, String> headers = new HashMap<String, String>();
String authValue = "Bearer " + apiToken;
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
The "Authorization" should not be a parameter. Its a header.
HttpPost request = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
Why don't you use OK Http for networking requests? Then you can do something like this:
val request = Request.Builder()
.url(yourUrl)
.header("Authorization", "Bearer $yourToken")
.post(yourBody)
.build()
Related
While unit testing my code of posting payload to an endpoint I am getting exception like HttpResponseProxy{HTTP/1.1 406 Not Acceptable}
HttpClient httpClient = mock(HttpClient.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
doReturn(HttpURLConnection.HTTP_CREATED).when(statusLine).getStatusCode();
doReturn(httpResponse).when(httpClient).execute(any());
HttpResponse response = service.postData("payload to be sent");
Assertions.assertNotNull(response);
Assertions.assertNotNull(response.getStatusLine().getStatusCode());
Assertions.assertNotNull(response.getEntity());
Assertions.assertNotNull(response.getHeaders("Authorization"));
Assertions.assertNotNull(response.getHeaders("Content-type"));
Actual Code -
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httppost = new HttpPost(endpoint);
httppost.setHeader("Authorization", "Bearer " + token);
httppost.setEntity(payloadString);
httppost.setHeader("Content-type", "application/json");
httpresponse = httpclient.execute(httppost);
responseCode = httpresponse.getStatusLine().getStatusCode();
}
return responseCode;
Please guide where I am going wrong and the right way to do this.
What could be the reason for a 400 (Bad request response) when using getMemberGroups API?
This is Java the code I'm using:
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "Bearer " + accessToken);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("securityEnabledOnly", "true"));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response;
final StatusLine statusLine;
try {
response = client.execute(request);
statusLine = response.getStatusLine();
} catch (IOException e) {
OutputUtil.printStacktrace(e);
return null;
}
Where url is "https://graph.microsoft.com/v1.0/me/getMemberGroups"
Another API call to "GET: memberOf" API does work. (with HttpGet object)
Try this :
String accessToken = "";
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://graph.microsoft.com/v1.0/me/getMemberGroups");
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "Bearer " + accessToken);
StringEntity requestEntity = new StringEntity("{\"securityEnabledOnly\": true}");
request.setEntity(requestEntity);
HttpResponse response;
final StatusLine statusLine;
response = client.execute(request);
statusLine = response.getStatusLine();
System.out.println(statusLine);
System.out.println(new String(response.getEntity().getContent().readAllBytes()));
Result:
I was wondering, using HttpClient and HttpPOST is there a way to post a complex JSON object as the body of the request? I did see an example of posting a simple key/value pair in the body (as shown below from this link: Http Post With Body):
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));
request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
However, I would need to post something like the following:
{
"value":
{
"id": "12345",
"type": "weird",
}
}
Is there a way for me to accomplish this?
ADDITIONAL INFORMATION
Doing the following:
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
results in an empty body on the server... hence i get a 400.
Thanks in advance!
HttpPost.setEntity() accepts StringEntity which extends AbstractHttpEntity. you can set it with any valid String of your choice:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
This worked for me!
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
String json = "{\"value\": {\"id\": \"12345\",\"type\": \"weird\"}}";
StringEntity entity = new StringEntity(json);
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
request.setEntity(entity);
request.setHeader("Content-type", "application/json");
HttpResponse resp = client.execute(request);
I am very new to this Apache http client. I have an URL to make a webservice call to one of the service. I was successfully executed with the GET request but I am trying to execute this with the POST request but I am not getting any response. I was unable to get the content from the entity.
My URL: "https://maps.googleapis.com/maps/api/place/details/xml?reference=CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA&sensor=true&key=key1";
This was executed with the GET method. Below u can see my code.
public class HttpClientPostExample {
public static void main(String[] args) throws ClientProtocolException,
IOException {
String url = "https://maps.googleapis.com/maps/api/place/details/xml?";
HttpClient client = HttpClientBuilder.create().build();
// HttpRequest httpRequest = HttpsClientImpl.createRequest("Post", url);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList
.add(new BasicNameValuePair(
"reference",
"CoQBcQAAAEZ7yCju-0lhU7sZIBBe_On9jYImWzZ9Zt5rIg1tX6zaH02dHrQMHF1LFHY1_yUuXzsUf6m6-rrQJ8Ec_mGxBYtV85Wyb4anakaUi3QuZj7ygJXB3Fd5x69k_4UnDKMmEBNa410vbCXgQOGIkHCbNpcbC8ENxmVlUrqiifmdfuLgEhCtPATMhFRdsjuyAL_j__OEGhTnqujRRMYy_5-kxzcqCdMY4_1dbA"));
nameValuePairList.add(new BasicNameValuePair("sensor", "true"));
nameValuePairList.add(new BasicNameValuePair("key",
"AIzaSyBA0Hu3is9qIJ5v6NEuofigk0y-aQwqiP0"));
httpPost.addHeader("User-Agent", "User-Agent");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
HttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
Header[] headerArray = response.getAllHeaders();
for (Header header : headerArray) {
System.out.println("Header Name: " + header.getName()
+ " Header Value: " + header.getValue());
}
}
Can any one help me on this. Is this the right approach to make a POST request...???
How can I get actual URL before firing/calling the execute method...???
Try to change your client instantiation technique from
HttpClient client = HttpClientBuilder.create().build();
to
DefaultHttpClient client = new DefaultHttpClient();
and to make sure that your entity has been fully consumed, make a call to EntityUtils.consume(entity) before showing the reponse headers:
...
HttpResponse response = client.execute(httpPost);
EntityUtils.consume(response.getEntity());
Header[] headerArray = response.getAllHeaders();
for (Header header : headerArray) {
System.out.println("Header Name: " + header.getName()
+ " Header Value: " + header.getValue());
}
I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}