I've been looking all over the internet for this, and I just haven't found an answer that works. I'm trying to make a bukkit plugin that sends data to an ingoing Slack webhook when a command is run. I've gotten to noticing the command running, but I have no idea how to send the JSON. (For those of you unfamiliar with Slack, the command inside a terminal window is curl -X POST --data-urlencode 'payload={"channel":"#slack-channel-id","username":"bot's username","text":"Self explanatory","icon_emoji":"The bot's icon"}' https://slack.com/custom/webhook/token/here I've been looking all over and googling for a good hour trying to find a way in Java to send this. But no matter what I try it doesn't work. Any help is appreciated, thanks
//You can use the following code it works!
slackWebhook is the https endpoint for the channel that you can get from custom_integration link
String payload = "payload={\"channel\": \"#channel_name\", \"text\": \"This is posted "
+ "to #ewe_gps_abacus_notif and comes from a bot named change-alert.\"}";
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(slackWebhook);
request.setEntity(entity);
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getStatusLine().getStatusCode());
Related
I have a cURL command:
curl -d '{"mobile_number":"09178005343", "pin":"1111"}' -H "Content:Type: application/json" -H "X-Gateway-Auth:authentication" -X POST https://localhost:9999/api/traces/%2f/login
I need to create an HTTP Request in Java API which will do the same thing. I don't have any idea regarding this. Thank you in advance for those who will take time to respond.
There are multiple ways to do it. Firstly, since you want to send a JSON object, you might want to use a JSON library, for example, Google's gson. But to make it easy you can just send the request as a String. Here is a sample code that sends your JSON to your URL.
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("https://localhost:9999/api/traces/%2f/login");
StringEntity params =new StringEntity("{\"mobile_number\":\"09178005343\", \"pin\":\"1111\"");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//Do what you want with the response
}catch (Exception ex) {
//If exception occurs handle it
} finally {
//Close the connection
}
I'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".
I am developing one application which is connecting to server to get some data.
In this I want to check first if application is connected to server or not. And then, if server is on or off? Based on the result I want to do my further manipulations.
So how do I get the result of server status?
Here is the code which I am using:
Code:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.23/sip_chat_api/getcountry.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
}
Maintaining session cookies is best choice here, please see how to use session cookie: How do I make an http request using cookies on Android?
here, before sending request to server, check for session cookie. If it exists, proceed for the communication.
Update:
The Java equivalent -- which I believe works on Android -- should be:
InetAddress.getByName(host).isReachable(timeOut)
Check getStatusLine() method of HttpResponse
any status code other than 200 means there is a problem , and each status codes points to different problems happened.
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/StatusLine.html#getStatusCode()
I am trying to find a solution to this the whole evening now...
I write an app which requests data from a web server. The Server answers in JSON format.
Everything works well except when I enter a umlaut like ä into my App.
In the following I assume the request URL is http://example.com/?q= and I am searching for "Jäger"
The correct call would then be h++p://example.com/?q=J%C3%A4ger
(Sorry for plus-signs but the spam protection doesnt let me post it correctly.)
So my problem is now:
When I give my URL String encoded or unencoded over to HttpGet it will always result in a doublee-encoded URL.
The Request to my Server is then http://example.com/?q=J%25C3%25A4ger (It encodes the percent signs)
which leads to the server searching in database for J%C3%A4ger what is obviously wrong.
So my question is how can I achive that if the user enters "Jäger" my app calls the correctly encoded URL?
Thanks for any help!
Here is the currently used code... Ist probably the worst possible idea I had...
URI url = new URI("http", "//example.com/?q=" + ((EditText)findViewById(R.id.input)).getText().toString(), null);
Log.v("MyLogTag", "API Request: " + url);
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse;
httpResponse = defaultClient.execute(httpGetRequest);
Update: Sorry, HttpParams isn't meant for request parameters but for configuring HttpClient.
On Android, you might want to use Uri.Builder, like suggested in this other SO answer:
Uri uri = new Uri.Builder()
.scheme("http")
.authority("example.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
HttpGet request = new HttpGet(uri.toString());
// This looks very tempting but does NOT set request parameters
// but just HttpClient configuration parameters:
// HttpParams params = new BasicHttpParams();
// params.setParameter("q", query);
// request.setParams(params);
HttpResponse response = defaultClient.execute(request);
String json = EntityUtils.toString(response.getEntity());
Outside of Android, your best bet is building the query string manually (with all the encoding hassles) or finding something similar to Android's Uri.Builder.
trying to access http://forum.worldoftanks.eu/index.php?app=members using apache HttpClient but keep getting 403. Can anyone help out?
Been fiddling with this piece as a starting point:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpRequestBase method = new HttpGet(theUrl);
String s = httpClient.execute(method, new BasicResponseHandler());
System.out.println(s);
httpClient.getConnectionManager().shutdown();
I don't think this is related to HttpClient. I tried this
$ wget http://forum.worldoftanks.eu/index.php?app=members
--2011-08-08 23:17:52-- http://forum.worldoftanks.eu/index.php?app=members
Resolving forum.worldoftanks.eu (forum.worldoftanks.eu)... 213.252.177.21, 213.2
52.177.20
Connecting to forum.worldoftanks.eu (forum.worldoftanks.eu)|213.252.177.21|:80..
. connected.
HTTP request sent, awaiting response... 403 Forbidden
2011-08-08 23:17:56 ERROR 403: Forbidden.
with no luck.
Yet I can hit it in the browser. It might be that there is some server logic returning 403s when an appropriate browser headers aren't sent. My next step would be to use FireBug and try to replicate the request as your browser makes it.
Also, try catching the exceptino
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
}