I made some research to solve my problem but sadly until now I couldn't. It's not such a big deal but I've stuck on it..
I need to make a search with some keywords in search engines such as google. I got two class here to do this:
package com.sh.st;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventSearch extends SearchScreen implements ActionListener {
public EventSearch(){
btsearch.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==btsearch){
String query=txtsearch.getText();
}
}
}
and
package com.sh.st;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class HttpRequest extends SearchScreen
{
URL url = new URL("google.com" + "?" + query).openConnection();
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8"); //Possible Incompatibility
InputStream response = connection.getInputStream();
}
So, txtsearch comes from another class named SearchScreen and I attributed the value to one string named query. I need to pass query to HttpRequest class and to do this I just extend, I'm sure it's wrong but I saw someone else doing this; and this is the first problem, how may I do this?
the second and most important I'm receiving syntax error:
I didn't fully understand the meaning and utility of "connection.setRequestProperty("Accept-Charset", "UTF-8");"
'course reading I can understand that is regarding the caracters that probably will come up from my request but even though the syntax error is not clear for me
I made research in links such:
How to send HTTP request in java?
getting text from password field
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
Using java.net.URLConnection to fire and handle HTTP requests
All of them have a good material but I can't fully understand everything on it and the part the I'm trying to follow is not working. Could anyone help me please?
Edit: [Topic Solved]
Try this code: (comments inlined)
// Fixed search URL; drop openConnection() at the end
URL url = new URL("http://google.com/search?q=" + query);
// Setup connection properties (this doesn't open the connection)
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
// Actually, open the HTTP connection
connection.connect();
// Setup a reader
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
// Read line by line
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println (line);
}
// Close connection
reader.close();
Related
I am trying to make a program where a user can asks GPT-3 a question through its API.
I tried to get GPT-3's assistant to design code for me, however there were some errors because it uses outdated information from 2021. Below is my modified code after going through the documentation, but I still cant get it to work, it is generating a 'java.io.FileNotFoundException' error.
I believe the problem is with the formatting of the completion section of my URL, however I am not sure. If anyone could tell me what's wrong it would be greatly appreciated.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ChatGPT{
public static void main(String[] args) throws IOException {
String prompt = "What country has the most moderate weather?";
String model = "text-curie-001";
String apiKey = /*My API key*/;
// Encode the prompt and construct the API request URL
String url = String.format(
"https://api.openai.com/v1/completions?model=%s&prompt=%s",
model,
URLEncoder.encode(prompt, "UTF-8")
);
// Create the request
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
// Make the request and retrieve the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
reader.close();
// Print the response
System.out.println(responseBody);
}
}
I know my API key is valid because changing the url to whats shown below outputs the appropriate information:
String url = String.format(
"https://api.openai.com/v1/models/%s",
model
);
the format "/v1/models/text-curie-001" outputs the details for the model 'text-curie-001'
the format "/v1/completions..." outputs a response based on the given prompt.
I need to consume a SOAP service, and I have seen on the spring tutorial that my java classes for consuming and receiving the services, can be automatically generated using a tool or a framework.
The thing is most tutorials rely on wsimport tool from the JDK...and after lots of hours trying I found out that for Java 11, this is deprecated.
After this I found this ,this, and this talking about some workarounds for this problem. I tried all of them, but my gradle.build starts generating dependencies issues around this libraries. I have tried to exclude the problematic libraries but it doesn´t solve the issue.
So I'm wondering how can I generate my SOAP client classes on a not so patched way?
Additional info: It's a contract first approach, the service is on the web and it is a ?wsdl url.
At the end, I just followed this tutorial, which was simple enough and allowed me to consume a SOAP web service and then build an XML file to process the info retrieved. Hopefully Java 11 will have some better support for this type of service on the near future, but meanwhile I solved my problem and maybe this post can be useful to someone with a similar task to perform.
ofcourse that I can share :) my coding:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
#Service
#Slf4j
public class GusGetCompanyRawXml {
public String getCompanyRawXmlData(String sessionKey, String polishVatId) {
String outputString = "";
try {
URL url = new URL("https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc");
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput =
"<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"\n"
+ "xmlns:ns=\"http://CIS/BIR/PUBL/2014/07\" xmlns:dat=\"http://CIS/BIR/PUBL/2014/07/DataContract\">\n"
+ "<soap:Header xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">\n"
+ "<wsa:To>https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc</wsa:To>\n"
+ "<wsa:Action>http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/DaneSzukajPodmioty</wsa:Action>\n"
+ "</soap:Header>\n"
+ "<soap:Body>\n"
+ "<ns:DaneSzukajPodmioty>\n"
+ "<ns:pParametryWyszukiwania>\n"
+ "<dat:Nip>"+polishVatId+"</dat:Nip>\n"
+ "</ns:pParametryWyszukiwania>\n"
+ "</ns:DaneSzukajPodmioty>\n"
+ "</soap:Body>\n"
+ "</soap:Envelope>";
byte[] buffer;
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "http://CIS/BIR/PUBL/2014/07/IUslugaBIRzewnPubl/Zaloguj";
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestProperty("sid", sessionKey);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.
//Read the response.
InputStreamReader inputStreamReader = new InputStreamReader(httpConn.getInputStream(), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//
String responseString = "";
//Write the SOAP message response to a String.
while ((responseString = bufferedReader.readLine()) != null) {
if (StringUtils.contains(responseString, "<")) {
String unescapedString = StringEscapeUtils.unescapeXml(responseString);
String remove = StringUtils.remove(unescapedString, "\r");
outputString = outputString + remove;
}
}
} catch (IOException e){
log.error("Get customer data from gus failed",e.getStackTrace());
}
return outputString;
}
}
public BlnInitBookData initTrans(String ccode, String license) {
BlnInitBookData initBookData = null;
try {
BlnInitBook request = new BlnInitBook();
request.setLicenseType(license);
request.setStrCinemaCode(ccode);
initBookData = ((BlnInitBookResponse) getWebServiceTemplate().marshalSendAndReceive(hosted_server_URL, request,
new SoapActionCallback("URL_of_SOAP_api"))).getServiceResponse1()
.getBlnInitBookData();
} catch (final Exception e) {
logger.error(this.getClass().getName() + e.getMessage);
}
return initBookData;}
In Java, use the WebServiceGatewaySupport class, It worked for me. I generated SOAP requests, response classes.
This program compiles successfully but when I try to run the program it gives me errors.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args)
throws Exception {
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter
(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
The following error occurs (I have attached the image):
Screenshot of errors
I am behind a proxy server. Does that make a problem in connecting to the internet? If so please post the solution that .. Thanks in advance.
You should do something similar:
1st of all put proxy information to system properties:
System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "proxyHost", "proxy_hostname" );
System.getProperties().put( "proxyPort", "8080" ); // or other proxy port
And then you need to do authentication on proxy, using something similar:
URL url = new URL("http://www.google.com");
URLConnection con = url.openConnection();
String pass = "MY_USERNAME:MY_PASS";
String encodedPass = base64Encode( pass );
con.setRequestProperty( "Proxy-Authorization", encodedPass );
Good luck.
Yes. Proxy settings can protect a standalone app from connecting to internet. If you know the proxy try using
-Dhttp.proxyHost=yourProxy & -Dhttp.proxyPort=proxyPort
These are VM arguments. If you are running it command line then use it as
java -Dhttp.proxyHost=yourProxy & -Dhttp.proxyPort=proxyPort Main
I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!
Really simple, or so I thought.
Java Code
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnectionTest {
private static final String TEST_URL = "http://localhost:3000/test/hitme";
public static void main(String[] args) throws IOException {
URLConnection urlCon = null;
URL url = null;
OutputStreamWriter osw = null;
try {
url = new URL(TEST_URL);
urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setRequestProperty("Content-Type", "text/plain");
osw = new OutputStreamWriter(urlCon.getOutputStream());
osw.write("HELLO WORLD");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (osw != null) {
osw.close();
}
}
}
}
TestController#hitme
def hitme
puts "SOMEONE IS HITTING ME!" * 100
puts request.env.inspect
end
When I run the Java code, I see nothing in my Rails Server Console. However, when I hit the URL in my browser, I get output as specified in TestController#hitme. I thought it would be simple, but haven't had any luck. Any ideas?
Thanks in advance!
You're probably getting an exception, which you aren't seeing, because you're swallowing it. At least print the exception in the catch block.
Even if this isn't the problem, your going to chase your tail a lot if you make a habit of swallowing errors.
I don't think you're actually sending any data until you call
urlCon.getInputStream();
Is it that your URL in your java code shows the controller name of "test" (test/hitme) but you mention that your controller name is TestController? i.e., the URL in your java code should be changed.
private static final String TEST_URL = "http://localhost:3000/TestController/hitme";
Don't fiddle around with URLConnection yourself, let Resty handle it.
Here's the code you would need to write (I assume you are getting text back):
import static us.monoid.web.Resty.*;
import us.monoid.web.Resty;
...
new Resty().text(TEST_URL, content("HELLO WORLD")).toString();