Skip to content

Instantly share code, notes, and snippets.

@hatimn02
Created July 26, 2016 07:56
Show Gist options
  • Save hatimn02/3ee5d66f257930253158e2f814e2f18a to your computer and use it in GitHub Desktop.
Save hatimn02/3ee5d66f257930253158e2f814e2f18a to your computer and use it in GitHub Desktop.
Java sample code
import org.json.simple.JSONObject;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class Socket {
public static void invoke() {
//Your authentication key
String authKey = "YourAuthKey";
//Prepare Url
URLConnection myURLConnection=null;
URL myURL=null;
BufferedReader reader=null;
//Socket Api
String mainUrl="http://flow.viasocket.com/trigger/sample_url/slack_integration"; //Replace with your socket api
mainUrl = mainUrl + "?";
//You can post data in both query params as well as in body
//Prepare parameter or query string
StringBuilder sbPostData= new StringBuilder(mainUrl);
sbPostData.append("owner="+encode("John Parker")); //URL encoding to deal with special characters and spaces
sbPostData.append("&lat="+"65.326");
sbPostData.append("&message="+encode("Hello World"));
//Prepare Json body
JSONObject jsonBody=new JSONObject();
jsonBody.put("Humble", "Jumble");
jsonBody.put("Greetings", "Hey, How r u?");
//Final url
mainUrl = sbPostData.toString();
try
{
//Prepare connection
myURL = new URL(mainUrl);
myURLConnection = myURL.openConnection();
myURLConnection.setDoOutput(true);
myURLConnection.setDoInput(true);
//Setting Auth-Key in header
myURLConnection.setRequestProperty ("Auth-Key", authKey);
//Setting Content-Type in header
myURLConnection.setRequestProperty ("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter wr= new OutputStreamWriter(myURLConnection.getOutputStream());
wr.write(jsonBody.toString());
wr.flush();
myURLConnection.connect();
reader= new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
//reading response
String response;
while ((response = reader.readLine()) != null)
//print response
System.out.println(response);
//finally close connection
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static String encode(String text){
try{
return URLEncoder.encode(text,"UTF-8");
}catch(IOException e){
e.printStackTrace();
return null;
}
}
public static void main(String gg[]){
Socket.invoke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment