This blog would be providing you one stop solution for the clean solutions towards solving the problem, instead of just giving just instruction and not actual code.

13 Oct 2013

How to insert data in Mongolab programatically in Java?

No comments :
Assumptions
  • Mongolab database is already created
  • Audience is aware of Java programming
Step-1: Get mongolab databse API key
1) Login to mongolab at below link.
https://mongolab.com
2) Click on username link on top right corner of the page.
3) Copy the URL and API key from the bottom of the page.
"https://api.mongolab.com/api/1/databases/{{database name}}/collections/{{collection name}}?apiKey={{API key}}"
Step-2: Java program to use the API key
    package poc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class InsertJSON {

 private final String USER_AGENT = "Mozilla/5.0";
 private static final String MONGOLAB_DATABASE = "MONGOLAB_DATABASE";
 private static final String MONGOLAB_COLLECTION = "MONGOLAB_COLLECTION";
 private static final String MONGOLAB_API_KEY = "b_6OqxduIanXrxocmvTsAXubns5iXYZ";
 private static final String _URL = "https://api.mongolab.com/api/1/databases/"+MONGOLAB_DATABASE+"/collections/"+MONGOLAB_COLLECTION+"?apiKey="+MONGOLAB_API_KEY;
 public static void main(String[] args) {

  try {
   for(int i=100;i<=200;i++){
    URL url = new URL(_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    String input = "{"+
      "\"_id\": \""+i+"\",    \"episode\": \"22\",    \"date\": \"12-Aug-2012\",    \"name\": \"Hitlardidi\",    \"channel\": \"Zee\",    \"keyword\": \"test\","+
      "\"poster\": \"http://funrulz.com/wp-content/uploads/2013/06/Hitler-Didi.jpg\",    \"site\": \"https://www.youtube.com/watch?v=xtIRohx67i8\"}";

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream())));
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
     System.out.println(output);
    }
    conn.disconnect();
   }

  } catch (MalformedURLException e) {

   e.printStackTrace();

  } catch (IOException e) {

   e.printStackTrace();

  }
 }
}

No comments :

Post a Comment