Help on on CS assignment
I need the code for the assignment!!!
(this is is my second time posting this, PLEASE DO NOT ANSWER TWICE as I want a varation of answers and methods)
Assignment 3: Getting Started with Web Requests and Bots
The Project is broken down into the following pieces:
PART 1 – Making Use of a REST API and Web Requests
●Make Web Requests to Receive Data (REST), you will need to learn more on what this is.
○You can use Postman (app) to test requests
■Get trending tags
●https://dev.twitter.com/rest/reference/get/trends/place
○Weather
■Get Local Temperature
●https://openweathermap.org/api
For example: You can hit a URL like : api.openweathermap.org/data/2.5/forecast?lat=35&lon=139
(example pic 1) http://imgur.com/a/uc2eS
The response format that you get is called JSON (Javascript Object Notation). You will want to read up more on this (http://codular.com/json).
A good JSON editor is: http://www.jsoneditoronline.org/ It can easily parse it and let you understand the JSON.
Your Java Program will need to parse the JSON to make use of the data. You will definitely need to use a library to parse the Json. GSON is a good library to use, look it up on your own.
Use this website for reference:
http://www.oracle.com/technetwork/articles/java/json-1973242.html
Ideally, you will want to make a method that you can call in your Java program that return this information to you.
For example a function like:
int getWeather(string city) -> returns the current temperature from the Weather API
PART 2 – Creating a Interfaceable Chat Bot
You will want to first create a simple program that can connect to the Chat Server. The chatserver we will be using is called FreeNode.
Here is some sample code to s
●Use Java.Net Library to create a Chat Server
○Directions are provided below
■You will expose your bot so anyone can interact with it
■Check next page for code sample
When the bot’s connected to the group chat it should read the messages and when a message matches a command it respond accordingly. This means if someone says “Weather 75080” it should return parse the words and query the weather API and return the information in a IRC-friendly format (“The weather’s going to be X with a high of Y and a low of Z.”
○Use command phrases that trigger a response
■“Weather 75080”
■“How’s the weather in 75080?”
○Use your wrapper and respond accordingly.
○It doesn’t have to use Natural Language Processing, keywords is fine
Here is some code to get you started with connecting to a bot on Freenode:
http://archive.oreilly.com/pub/h/1966
(example pic 2) http://imgur.com/a/KbWPu
I am trying to get student visitors next week or someone from Makerspace Workshops to review the following with you:
1.)Web Requests in Java
Making REST calls using Java. It will introduce you to how the web works and you will be able to make functions that can fetch data
2.)Building an IRC client
Making an IRC client using Java. This should introduce you to Sockets and be able to connect and interact with an IRC server. You’ll be able to make a functional Hello World bot.
Expert Answer
Connection.java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class Connection {
private final String USER_AGENT1 = “Mozilla/5.0”;public static void main(String[] args) throws Exception {
Connection http = new Connection();
System.out.println(“Send Http GET request”);
http.sendGet();
System.out.println(“nSend Http POST request”);
http.sendPost();}
// HTTP GET request
private void sendGet() throws Exception {
String url = “http://www.google.com/search?q=mkyong1”;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod(“GET”);
//add request
con.setRequestProperty(“User-Agent”, USER_AGENT1);int responseCode = con.getResponseCode();
System.out.println(“nSending ‘GET’ request to URL : ” + url);
System.out.println(“Response Code : ” + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}// HTTP POST request
private void sendPost() throws Exception {
String url = “https://selfsolve.apple.com/wcResults.do”;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod(“POST”);
con.setRequestProperty(“User-Agent”, USER_AGENT1);
con.setRequestProperty(“Accept-Language”, “en-US,en;q=0.5”);
String urlParameters = “id=C02G8416DRJM&city=&local=&call=&number=12345”;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(“nSending ‘POST’ request to URL : ” + url);
System.out.println(“Post parameters : ” + urlParameters);
System.out.println(“Response Code : ” + responseCode);
BufferedReader in = new BufferedReadernew InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());}}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class Client {
private final String USER_AGENT1 = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
Client http = new Client();
System.out.println("Send Http GET request");
http.sendGet();
System.out.println("n Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT1);
HttpResponse response = client.execute(request);
System.out.println("nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT1);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("id", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("city", ""));
urlParameters.add(new BasicNameValuePair("local", ""));
urlParameters.add(new BasicNameValuePair("call", ""));
urlParameters.add(new BasicNameValuePair("number", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}}
Webrequest.java
import java.net.*;
import java.io.*;
import java.util.*;
class IrcSenderSimple {
static void sendString(BufferedWriter bw, String str) {
try {
bw.write(str + “rn”);
bw.flush();
}
catch (Exception e) {
System.out.println(“Exception: “+e);
}
}
public static void main(String args[]) {
try {
String server = “chat1.ustream.tv”;
int port = 6667;
String city = “hyd”;
String number = “#bot-test-ch”;
String message = “hi, all”;
Socket socket = new Socket(server,port);
System.out.println(“*** Connected to server.”);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
System.out.println(“*** Opened OutputStreamWriter.”);
BufferedWriter bwriter = new BufferedWriter(outputStreamWriter);
System.out.println(“*** Opened BufferedWriter.”);
sendString(bwriter,”NICK “+city);
sendString(bwriter,”USER chatterBot 8 * :chatterBot 0.0.1 Java IRC Bot – www.chat.org”);
sendString(bwriter,”JOIN “+number);
/*
// サーバーからの応答確認
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
BufferedReader breader = new BufferedReader(inputStreamReader);
String line = null;
int tries = 1;
while ((line = breader.readLine()) != null) {
System.out.println(“>>> “+line);
int firstSpace = line.indexOf(” “);
int secondSpace = line.indexOf(” “, firstSpace + 1);
if (secondSpace >= 0) {
String code = line.substring(firstSpace+1, secondSpace);
if (code.equals(“004”)) {
break;
}
}
}
*/
sendString(bwriter,”PRIVMSG “+number+” :”+message);
bwriter.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}