I try to run this java program which returns a webpage in my webroot folder
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class WebServer {
static ServerSocket requestListener;
static Socket requestHandler;
static Scanner requestReader, pageReader;
static DataOutputStream pageWriter;
static String HTTPMessage;
static String requestedFile;
public static int HTTP_PORT = 12346;
public static void main(String[] args) {
try {
requestListener = new ServerSocket(HTTP_PORT);
System.out.println("Waiting For IE to request a page:");
requestHandler = requestListener.accept();
System.out.println("Page Requested: Request Header:");
requestReader = new Scanner(new InputStreamReader(
requestHandler.getInputStream()));
//THis is the part where its throwing the error
int lineCount = 0;
do {
lineCount++; // This will be used later
HTTPMessage = requestReader.next();
System.out.println(HTTPMessage);
if (lineCount == 1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}
// localhost:12346/default.htm
// HTTPMessage = requestReader.nextLine();
pageReader = new Scanner(new File(requestedFile));
pageWriter = new DataOutputStream(
requestHandler.getOutputStream());
while (pageReader.hasNext()) {
String s = pageReader.nextLine();
// System.out.println(s);
pageWriter.writeBytes(s);
}
// Tells the Browser we’re done sending
pageReader.close();
pageWriter.close();
requestHandler.close();
} while (HTTPMessage.length() != 0);
} catch (Exception e) {
System.out.println(e.toString());
System.out.println("\n");
e.printStackTrace();
}
}
}
and I get this error message. I am supposed to get a webpage in IE but all I get this error message.
Waiting For IE to request a page:
Page Requested: Request Header:
GET
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
at java.lang.String.substring(Unknown Source)
at WebServer.main(WebServer.java:39)
This error is being thrown because the String 'HTTPMessage' does not contain the string 'HTTP/1.1'. Hence
HTTPMessage.indexOf("HTTP/1.1") => returns -1
So inside yoour substring function this is whats getting passed :
HTTPMessage.substring(5, -2);
Hence the error.
To solve this error, you should first try to check if HTTPMessage contains the required string and then try to compute the substring. Make the following change :
if (lineCount == 1 && HTTPMessage.indexOf("HTTP/1.1") != -1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}
Related
I'm writing a very tiny, very sh*tty web server just for fun. It was working fine with GET requests or returning a 404. And worked very briefly working with POST requests. And now it just hangs on any POST request.
Here is the relevant bit of code. As you can see I put in some logging to both System.out and to a file. The logging to System.out works, but the logging to file never happens. If I remove the logging to file, it still hangs on the line after System.out log. I included the few lines previous so you can see that it is the exact same code as returning a 404. 404 works, but POST doesn't. This is using a ServerSocket. I'm at a complete loss at this point. Would appreciate any insight.
Edit: Have included the main and sendResponse methods in case there is anything in there that might be causing this.
Edit #2: Ima just post the whole thing.
package beerio;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Beerio {
public static void main( String[] args ) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(80)) {
while (true) {
try (Socket client = serverSocket.accept()) {
handleClient(client);
}
catch(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
BufferedWriter writer = new BufferedWriter(new FileWriter("errorlog.txt", true));
writer.append(System.lineSeparator());
writer.append(sw.toString());
writer.append(System.lineSeparator());
writer.close();
continue;
}
}
}
}
private static void handleClient(Socket client) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
//make request into string. this only parses until the first blank line
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()) {
requestBuilder.append(line + "\r\n");
}
//split string and parse into request info
String request = requestBuilder.toString();
String[] requestsLines = request.split("\r\n");
String[] requestLine = requestsLines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
String version = requestLine[2];
String host = requestsLines[1].split(" ")[1];
List<String> headers = new ArrayList<>();
for (int h = 2; h < requestsLines.length; h++) {
String header = requestsLines[h];
headers.add(header);
}
//rest of request contains post info. parse that here
if(method.equals("POST")) {
String parameters;
parameters = br.readLine();
String[] temp = parameters.split("&");
String[][] params = new String[temp.length][2];
for(int i=0; i<temp.length; i++) {
params[i][0] = temp[i].substring(0,temp[i].indexOf("="));
params[i][1] = temp[i].substring(temp[i].indexOf("=")+1);
}
}
Path filePath = getFilePath(path);
if (method.equals("GET")) {
System.out.println("doGet");
if (Files.exists(filePath)) {
// file exist
String contentType = guessContentType(filePath);
sendResponse(client, "200 OK", contentType, Files.readAllBytes(filePath));
} else {
// 404
byte[] notFoundContent = "<h1>Not found :(</h1>".getBytes();
sendResponse(client, "404 Not Found", "text/html", notFoundContent);
}
} else if(method.equals("POST")){
byte[] postContent = "<h1>POST Failed Successfully</h1>".getBytes();
sendResponse(client, "200 OK", "text/html", postContent);
}
}
private static void sendResponse(Socket client, String status, String contentType, byte[] content) throws IOException {
OutputStream clientOutput = client.getOutputStream();
clientOutput.write(("HTTP/1.1 " + status+"/r/n").getBytes());
clientOutput.write(("ContentType: " + contentType + "\r\n").getBytes());
clientOutput.write("\r\n".getBytes());
clientOutput.write(content);
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
client.close();
}
private static Path getFilePath(String path) {
if ("/".equals(path)) {
path = "\\index.html";
}
return Paths.get("C:\\Users\\shawn\\beerio\\beerio\\tmp\\www", path);
}
private static String guessContentType(Path filePath) throws IOException {
return Files.probeContentType(filePath);
}
}
Keep getting this error
"java.util.NoSuchElementException: No line found error java"
and searched through code so many times and cant see to find problems heres my files can anyone help?
Am currently doing this as an assignment and am trying to transfer it from unthreaded to threaded and in the process came up with this error!!
This is the Client class
package Client;
import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmailClient {
public static void main(String[] args) {
try
{
// Step 1 (on consumer side) - Establish channel of communication
Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT);
// Step 3) Build output and input objects
OutputStream out = dataSocket.getOutputStream();
PrintWriter output = new PrintWriter(new OutputStreamWriter(out));
InputStream in = dataSocket.getInputStream();
Scanner input = new Scanner(new InputStreamReader(in));
Scanner keyboard = new Scanner(System.in);
String message = "";
while(!message.equals(EmailServiceDetails.END_SESSION))
{
displayMenu();
int choice = getNumber(keyboard);
String response = "";
if(choice >=0 && choice < 3)
{
switch (choice)
{
case 0:
message = EmailServiceDetails.END_SESSION;
// Send message
output.println(message);
output.flush();
response = input.nextLine();
if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
{
System.out.println("Session ended.");
}
break;
case 1:
message = sendEmail(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
{
System.out.println("Email sent successfully");
}
else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
{
System.out.println("Sorry, the email could not be sent at this time.");
}
break;
case 2:
message = viewUnread(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.NO_UNREAD))
{
System.out.println("No unread mails found for that account.");
}
else
{
ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
System.out.println("Unread Emails:");
for(Email e: unreadMails)
{
System.out.println(e);
}
}
break;
}
if(response.equals(EmailServiceDetails.UNRECOGNISED))
{
System.out.println("Sorry, that request cannot be recognised.");
}
}
else
{
System.out.println("Please select an option from the menu");
}
}
System.out.println("Thank you for using the Email system.");
dataSocket.close();
}catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
public static void displayMenu()
{
System.out.println("0) Exit");
System.out.println("1) Send an email");
System.out.println("2) View all unread mails");
}
public static int getNumber(Scanner keyboard)
{
boolean numberEntered = false;
int number = 0;
while(!numberEntered)
{
try{
number = keyboard.nextInt();
numberEntered = true;
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
keyboard.nextLine();
}
}
keyboard.nextLine();
return number;
}
public static String sendEmail(Scanner keyboard)
{
System.out.println("Please enter the sender of this email:");
String sender = keyboard.nextLine();
// Get recipient information
String anotherRecipient = "Y";
ArrayList<String> recipients = new ArrayList();
while(anotherRecipient.equalsIgnoreCase("Y"))
{
System.out.println("Enter the recipient's email address:");
String recipient = keyboard.nextLine();
recipients.add(recipient);
System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
anotherRecipient = keyboard.nextLine();
}
System.out.println("Please enter the email subject:");
String subject = keyboard.nextLine();
System.out.println("Please enter the message body:");
String body = keyboard.nextLine();
// Get attachment information
ArrayList<String> attachments = new ArrayList();
System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
String anotherAttachment = keyboard.nextLine();
while(anotherAttachment.equalsIgnoreCase("Y"))
{
System.out.println("Enter the attachment information:");
String attachment = keyboard.nextLine();
attachments.add(attachment);
System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
anotherAttachment = keyboard.nextLine();
}
long timestamp = new Date().getTime();
String response = null;
Email e = null;
if(attachments.size() > 0)
{
e = new Email(sender, recipients, subject, body, timestamp, attachments);
}
else
{
e = new Email(sender, recipients, subject, body, timestamp);
}
response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
return response;
}
public static String viewUnread(Scanner keyboard)
{
System.out.println("Please enter the name of the email account you wish to see unread mail for:");
String recipient = keyboard.nextLine();
String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
return response;
}
}
--------------------------------------------------------------------------------
This is Server
---------------
package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EmailServer {
public static void main(String[] args) {
try{
// Set up a connection socket for other programs to connect to
ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
// Create the list of emails to be stored and worked with
EmailStore emails = new EmailStore();
boolean continueRunning = true;
int threadCount = 0;
while(continueRunning)
{
// Step 2) wait for incoming connection and build communications link
Socket dataSocket = listeningSocket.accept();
threadCount++;
System.out.println("The server has now accepted " + threadCount + " clients");
// Step 3) Build thread
// Thread should be given:
// 1) a group to be stored in
// 2) a name to be listed under
// 3) a socket to communicate through
// 4) Any extra information that should be shared
EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
newClient.start();
}
listeningSocket.close();
}
catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------
This is ServerThread
---------------
package Server;
import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author User
*/
public class EmailThread extends Thread {
private Socket dataSocket;
private Scanner input;
private PrintWriter output;
private int number;
private EmailStore emails;
public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {
try {
// Save the data socket used for communication between the thread and the Client
this.dataSocket = dataSocket;
// Save the id of the thread to identify output
// Save the id of the thread to identify output
this.number = number;
input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
// Create the stream for writing to the Client
output = new PrintWriter(this.dataSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
}
}
#Override
public void run() {
{
String incomingMessage = "";
String response;
try {
while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
// Wipe the response to make sure we never use an old value
response = null;
// take in information from the client
incomingMessage = input.nextLine();
System.out.println("Received message: " + incomingMessage);
// Break up information into components
String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);
// Confirm that the command was correctly formatted
// Did it include more than just the command text?
if (components.length > 1) {
CommandFactory factory = new CommandFactory();
// Figure out which command was sent by the client
// I.e. what does the client want to do?
Command command = factory.createCommand(components[0]);
// Take the remaining text the client sent (i.e. all the information provided)
// and execute the requested action (e.g. store the new mail, get all sent mails etc)
response = command.createResponse(components[1], emails);
} else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
response = EmailServiceDetails.SESSION_TERMINATED;
} else {
// If information was missing, set the response to inform the
// client that the command wasn't recognised
response = EmailServiceDetails.UNRECOGNISED;
}
// Send back the computed response
output.println(response);
output.flush();
}
} catch (Exception e) {
System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
} finally {
try {
// Shut down connection
System.out.println("\n* Closing connection with client #" + number + "... *");
dataSocket.close();
} catch (IOException e) {
System.out.println("Unable to disconnect: " + e.getMessage());
System.exit(1);
}
}
}
}
}
--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;
import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class EmailStore
{
private ArrayList<Email> emailList = new ArrayList();
public boolean addMail(Email newEmail)
{
return emailList.add(newEmail);
}
public boolean removeMail(Email mailToBeDeleted)
{
return emailList.remove(mailToBeDeleted);
}
public ArrayList<Email> findEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient
.filter(email -> email.getRecipients().contains(recipient))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
public ArrayList<Email> findEmailBySender(String sender)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails matching the specified sender
.filter(email -> email.getSender().equals(sender))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
// Methods to mark emails as read
// Provide a version that marks multiple mails as read AND a version that
// marks a single email as read
public void markMultipleAsRead(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsRead(e);
}
}
public void markAsRead(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsRead(true);
}
}
// Methods to mark emails as spam
// Provide a version that marks multiple mails as spam AND a version that
// marks a single email as spam
public void markAsSpam(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsSpam(true);
}
}
public void markMultipleAsSpam(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsSpam(e);
}
}
public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient AND the email is not unread
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
}
-------
Help Appreciated
-
----------
Help would be great appreciated as the frustration levels are at a high!!
This answer is a wild guess but in case 1 of the switch statement of the main method you are calling the input.nextLine() scanner which it might not contain information at that time. It is possible that you have to check if data arrived by using the hasNext() method first.
Also in the last method when you are collecting the email classes you don't really need to cast. It can be done like this:
results = emailList.stream()
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
.collect(Collectors.toCollection(ArrayList::new));
Hi Im figuring out this program but keep getting null as the answer. Any help will be appreciated. I cant use any external methods for this and have to declare a static method. Here is my code:
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class Links {
private static ArrayList<String> links;
public static ArrayList<String> getHTMLLinksFromPage(String location) {
String webpage = location;
for(int i = 0; i<webpage.length()-6; i++) {
if(webpage.charAt(i) == 'h' && webpage.charAt(i+1) == 'r') {
for(int k = i; k<webpage.length();k++ ){
if(webpage.charAt(k) == '>'){
String link = webpage.substring(i+6,k-1);
links.add(link);
// Break the loop
k = webpage.length();
}
}
}
}
return links;
}
public static void main(String[] args) throws IOException{
String address = "http://horstmann.com/index.html.";
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
String webpage = in.next();
ArrayList<String> x = getHTMLLinksFromPage(webpage);
System.out.println(x);
}
}
There are a few issues with your code:
Firstly you did not initialize your ArrayList called links.
Secondly there was an extra . at the end of your URL which caused a FileNotFoundException.
Also to break out of a for loop you should use the break statement.
Thirdly you are reading the web page incorrectly. You only call scanner.next() once which only reads the first token of the webpage. in this case <?xml. To read the whole web page you need to keep calling scanner.next().
Instead of using a Scanner though, I believe that using a InputStreamReader and BufferedReader would be faster.
So your code instead should look like this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Links {
public static void main(String[] args) throws IOException {
URL pageLocation = new URL("http://horstmann.com/index.html");
HttpURLConnection urlConnection = (HttpURLConnection) pageLocation.openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder response = new StringBuilder();
String line;
while((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
System.out.println(getHTMLLinksFromPage(response.toString()));
}
private static List<String> getHTMLLinksFromPage(final String webPage) {
List<String> links = new ArrayList<>();
for(int i = 0; i < webPage.length()-6; i++) {
if(webPage.charAt(i) == 'h' && webPage.charAt(i+1) == 'r') {
for(int j = i; j < webPage.length(); j++ ){
if(webPage.charAt(j) == '>'){
String link = webPage.substring(i+6,j-1);
links.add(link);
break;
}
}
}
}
return links;
}
}
Output:
[styles.css" rel="stylesheet" type="text/css", mailto:cay#horstmann.com, http://horstmann.com/caypubkey.txt, http://www.uni-kiel.de/, an-Albrechts-Universität</, http://www.kiel.de/, http://www.syr.edu/, http://www.umich.edu/, http://www.mathcs.sjsu.edu/, unblog/index.html, https://plus.google.com/117406678785944293188/posts, http://www.sjsu.edu/people/cay.horstmann, http://horstmann.com/quotes.html, http://horstmann.com/resume.html, http://www.family-horstmann.net/, http://horstmann.com/javaimpatient/index.html, http://horstmann.com/java8/index.html, http://horstmann.com/scala/index.html, http://horstmann.com/python4everyone.html, http://horstmann.com/bigjava.html, http://horstmann.com/bigjava.html, http://horstmann.com/bjlo.html, http://horstmann.com/bjlo.html, http://www.wiley.com/college/sc/horstmann/, http://horstmann.com/bigcpp.html, http://horstmann.com/cpp4everyone/index.html, http://horstmann.com/corejava.html, http://corejsf.com/, http://horstmann.com/design_and_patterns.html, http://horstmann.com/PracticalOO.html, http://horstmann.com/mood.html, http://horstmann.com/mcpp.html, http://codecheck.it, http://horstmann.com/violet/index.html, http://horstmann.com/safestl.html, http://www.stlport.org/, http://horstmann.com/cpp/pitfalls.html, http://horstmann.com/cpp/iostreams.html, http://code.google.com/p/twisty/, http://frotz.sourceforge.net/, http://www.vaxdungeon.com/Infocom/, http://horstmann.com/applets/RoadApplet/RoadApplet.html, http://horstmann.com/applets/Retire/Retire.html, http://horstmann.com/corejava.html, http://horstmann.com/applets/WeatherApplet/WeatherApplet.html, http://horstmann.com/corejava.html, http://horstmann.com/applets/Intersection/Intersection.html]
I'm trying to get a JSON format of all the websites found when querying google.
Code:
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* Created by Vlad on 19/03/14.
*/
public class Query {
public static void main(String[] args){
try{
String arg;
arg = "random";
URL url = new URL("GET https://www.googleapis.com/customsearch/v1?key=&cx=017576662512468239146:omuauf_lfve&q=" + arg);
InputStreamReader reader = new InputStreamReader(url.openStream(),"UTF-8");
int ch;
while((ch = reader.read()) != -1){
System.out.print(ch);
}
}catch(Exception e)
{
System.out.println("This ain't good");
System.out.println(e);
}
}
}
Exception:
java.net.MalformedURLException: no protocol: GET https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=random
You should delete the GET at the beginning ;)
You should replace your code by :
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=" + arg);
Url never start by GET or POSTor anything like that ;)
Urls are supposed to start with a protocol for transfer and GET https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=random is starting with GET, that is why the exception is received.
Change it to https://www.googleapis.com/customsearch/v1?key=AIzaSyCS26VtzuCs7bEpC821X_l0io_PHc4-8tY&cx=017576662512468239146:omuauf_lfve&q=random
package com.intel.bluetooth.javadoc.ServicesSearch;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.obex.*;
//import java.util.Vector;
public class ObexPutClient {
public static void main(String[] args) throws IOException, InterruptedException {
String serverURL = null; // = "btgoep://0019639C4007:6";
if ((args != null) && (args.length > 0)) {
serverURL = args[0];
}
if (serverURL == null) {
String[] searchArgs = null;
// Connect to OBEXPutServer from examples
// searchArgs = new String[] { "11111111111111111111111111111123" };
**ServicesSearch**.main(searchArgs);
if (ServicesSearch.serviceFound.size() == 0) {
System.out.println("OBEX service not found");
return;
}
// Select the first service found
serverURL = (String)ServicesSearch.serviceFound.elementAt(0);
}
System.out.println("Connecting to " + serverURL);
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
byte data[] = "Hello world!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
}
Can anyone help me?The error is in bold letters.
Thank You
Do you have ServicesSearch created? Or included? and imported (in case it exists in some other package).
Show us the code, and tell us more.