Cannot access azure blobs through rest api - java

I was able to create a Container in Storage Account and upload a blob to it through the Client Side Code.
I was able to make the blob available for Public access as well , such that when I hit the following query from my browser, I am able to see the image which I uploaded.
https://MYACCOUNT.blob.core.windows.net/MYCONTAINER/MYBLOB
I now have a requirement to use the rest service to retrieve the contents of the blob. I wrote down the following java code.
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class GetBlob {
public static void main(String[] args) {
String url="https://MYACCOUNT.blob.core.windows.net/MYCONTAINER/MYBLOB";
try {
System.out.println("RUNNIGN");
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("Authorization", createQuery());
connection.setRequestProperty("x-ms-version", "2009-09-19");
InputStream response = connection.getInputStream();
System.out.println("SUCCESSS");
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String createQuery()
{
String dateFormat="EEE, dd MMM yyyy hh:mm:ss zzz";
SimpleDateFormat dateFormatGmt = new SimpleDateFormat(dateFormat);
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
String date=dateFormatGmt.format(new Date());
String Signature="GET\n\n\n\n\n\n\n\n\n\n\n\n" +
"x-ms-date:" +date+
"\nx-ms-version:2009-09-19" ;
// I do not know CANOCALIZED RESOURCE
//WHAT ARE THEY??
// +"\n/myaccount/myaccount/mycontainer\ncomp:metadata\nrestype:container\ntimeout:20";
String SharedKey="SharedKey";
String AccountName="MYACCOUNT";
String encryptedSignature=(encrypt(Signature));
String auth=""+SharedKey+" "+AccountName+":"+encryptedSignature;
return auth;
}
public static String encrypt(String clearTextPassword) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(clearTextPassword.getBytes());
return new sun.misc.BASE64Encoder().encode(md.digest());
} catch (NoSuchAlgorithmException e) {
}
return "";
}
}
However , I get the following error when I run this main class...
RUNNIGN
java.io.IOException: Server returned HTTP response code: 403 for URL: https://klabs.blob.core.windows.net/delete/Blob_1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at main.MainClass.main(MainClass.java:61)
Question1: Why this error, did I miss any header/parameter?
Question2: Do I need to add headers in the first place, because I am able to hit the request from the browser without any issues.
Question3: Can it be an SSL issue? What is the concept of certificates, and how and where to add them? Do I really need them? Will I need them later, when I do bigger operations on my blob storage(I want to manage a thousand blobs)?
Will be thankful for any reference as well, within Azure and otherwise that could help me understand better.
:D
AFTER A FEW DAYS
Below is my new code for PutBlob I azure. I believe I have fully resolved all header and parameter issues and my request is perfect. However I am still getting the same 403. I do not know what the issue is. Azure is proving to be pretty difficult.
A thing to note is that the containers name is delete, and I want to create a blob inside it, say newBlob. I tried to initialize the urlPath in the code below with both "delete" and "delete/newBlob".
Does not work..
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class Internet {
static String key="password";
static String account="klabs";
private static Base64 base64 ;
private static String createAuthorizationHeader(String canonicalizedString) throws InvalidKeyException, Base64DecodingException, NoSuchAlgorithmException, IllegalStateException, UnsupportedEncodingException {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(base64.decode(key), "HmacSHA256"));
String authKey = new String(base64.encode(mac.doFinal(canonicalizedString.getBytes("UTF-8"))));
String authStr = "SharedKey " + account + ":" + authKey;
return authStr;
}
public static void main(String[] args) {
System.out.println("INTERNET");
String key="password";
String account="klabs";
long blobLength="Dipanshu Verma wrote this".getBytes().length;
File f = new File("C:\\Users\\Dipanshu\\Desktop\\abc.txt");
String requestMethod = "PUT";
String urlPath = "delete";
String storageServiceVersion = "2009-09-19";
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:sss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = fmt.format(Calendar.getInstance().getTime()) + " UTC";
String blobType = "BlockBlob";
String canonicalizedHeaders = "x-ms-blob-type:"+blobType+"\nx-ms-date:"+date+"\nx-ms-version:"+storageServiceVersion;
String canonicalizedResource = "/"+account+"/"+urlPath;
String stringToSign = requestMethod+"\n\n\n"+blobLength+"\n\n\n\n\n\n\n\n\n"+canonicalizedHeaders+"\n"+canonicalizedResource;
try {
String authorizationHeader = createAuthorizationHeader(stringToSign);
URL myUrl = new URL("https://klabs.blob.core.windows.net/" + urlPath);
HttpURLConnection connection=(HttpURLConnection)myUrl.openConnection();
connection.setRequestProperty("x-ms-blob-type", blobType);
connection.setRequestProperty("Content-Length", String.valueOf(blobLength));
connection.setRequestProperty("x-ms-date", date);
connection.setRequestProperty("x-ms-version", storageServiceVersion);
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
System.out.println(String.valueOf(blobLength));
System.out.println(date);
System.out.println(storageServiceVersion);
System.out.println(stringToSign);
System.out.println(authorizationHeader);
System.out.println(connection.getDoOutput());
DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
// Send request
outStream.writeBytes("Dipanshu Verma wrote this");
outStream.flush();
outStream.close();
DataInputStream inStream = new DataInputStream(connection.getInputStream());
System.out.println("BULLA");
String buffer;
while((buffer = inStream.readLine()) != null) {
System.out.println(buffer);
}
// Close I/O streams
inStream.close();
outStream.close();
} catch (InvalidKeyException | Base64DecodingException | NoSuchAlgorithmException | IllegalStateException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I know only a proper code reviewer might be able to help me, please do it if you can.
Thanks

Question1: Why this error, did I miss any header/parameter?
Most likely you're getting this error is because of incorrect signature. Please refer to MSDN documentation for creating correct signature: http://msdn.microsoft.com/en-us/library/azure/dd179428.aspx. Unless your signature is correct you'll not be able to perform operations using REST API.
Question2: Do I need to add headers in the first place, because I am
able to hit the request from the browser without any issues.
In your current scenario, because you can access the blob directly (which in turn means the container in which the blob exist has Public or Blob ACL) you don't really need to use REST API. You can simply make a HTTP request using Java and read the response stream which will have blob contents. You would need to go down this route if the container ACL is Private because in this case your requests need to be authenticated and the code above creates an authenticated request.
Question3: Can it be an SSL issue? What is the concept of
certificates, and how and where to add them? Do I really need them?
Will I need them later, when I do bigger operations on my blob
storage(I want to manage a thousand blobs)?
No, it is not an SSL issue. Its an issue with incorrect signature.

Finally found the mistake!!
In the code above , I was using a String "password" as key for my SHA2
base64.decode(key)
It should have been the key associated with my account with AZURE.
Silly One!! Took me 2 weeks to find.

Related

Error in formating the URL for chatGPT's API

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.

SOAP client on Java 11

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.

Copy of InputStream blocks with Jetty HTTP client using an InputStreamResponseListener

Im am using Jetty 9.4.8 HTTP client and want to write a stream of incoming data to a file. Currently I am using an InputStreamResponseListener and IOUtils.copy(..) writing to a FileOutputStream. I have also tried Files.copy().
InputStreamResponseListener streamResponseListener = new InputStreamResponseListener();
request.send(streamResponseListener);
if(streamResponseListener.get(5, TimeUnit.MINUTES).getStatus() == 200) {
OutputStream outputStream = null;
try {
TMP_FILE.toFile().createNewFile();
outputStream = new FileOutputStream(TMP_FILE.toFile());
IOUtils.copy(inputStream, outputStream);
} catch(IOException e) {
this.getLogService().log(..)
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
// NOT REACHED IN CASE InputStream is BLOCKED FOR SOME REASON
}
However, the copy methods seem to block after all bytes have been received. Why could this happen and how can I avoid this?
Headers of the HTTP content requested:
Date: Wed, 23 May 2018 16:46:06 GMT
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=".."
Content-Length: 613970044
Server: Jetty(9.4.8.v20171121)
IOUtils from Apache Commons IO Version 2.4
Here's a working example of your codebase, using only Java and Jetty.
This is requesting content from a server that is known to comply with the HTTP spec.
package demo.jettyclient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.ssl.SslContextFactory;
public class DownloadUrl
{
public static void main(String[] args) throws Exception
{
String uriString = "https://upload.wikimedia.org/wikipedia/en/a/a1/Jetty_logo.png?download";
if (args.length >= 1)
uriString = args[0];
URI srcUri = URI.create(uriString);
SslContextFactory ssl = new SslContextFactory(true);
HttpClient client = new HttpClient(ssl);
try
{
client.start();
Request request = client.newRequest(srcUri);
System.out.printf("Using HttpClient v%s%n", getHttpClientVersion());
System.out.printf("Requesting: %s%n", srcUri);
InputStreamResponseListener streamResponseListener = new InputStreamResponseListener();
request.send(streamResponseListener);
Response response = streamResponseListener.get(5, TimeUnit.SECONDS);
if (response.getStatus() != HttpStatus.OK_200)
{
throw new IOException(
String.format("Failed to GET URI [%d %s]: %s",
response.getStatus(),
response.getReason(),
srcUri));
}
Path tmpFile = Files.createTempFile("tmp", ".dl");
try (InputStream inputStream = streamResponseListener.getInputStream();
OutputStream outputStream = Files.newOutputStream(tmpFile))
{
IO.copy(inputStream, outputStream);
}
System.out.printf("Downloaded %s%n", srcUri);
System.out.printf("Destination: %s (%,d bytes)%n", tmpFile.toString(), Files.size(tmpFile));
}
finally
{
client.stop();
}
}
private static String getHttpClientVersion()
{
ClassLoader cl = HttpClient.class.getClassLoader();
// Attempt to use maven pom properties first
String pomResource = "/META-INF/maven/org/eclipse/jetty/jetty-client/pom.properties";
URL url = cl.getResource(pomResource);
if (url != null)
{
try (InputStream in = url.openStream())
{
Properties props = new Properties();
props.load(in);
String version = props.getProperty("version");
if (StringUtil.isNotBlank(version))
return version;
}
catch (IOException ignore)
{
}
}
// Attempt to use META-INF/MANIFEST.MF
String version = HttpClient.class.getPackage().getImplementationVersion();
if (StringUtil.isNotBlank(version))
return version;
return "<unknown>";
}
}
When run, this results in ...
2018-05-23 10:52:08.401:INFO::main: Logging initialized #325ms to org.eclipse.jetty.util.log.StdErrLog
Using HttpClient v9.4.9.v20180320
Requesting: https://upload.wikimedia.org/wikipedia/en/a/a1/Jetty_logo.png?download
Downloaded https://upload.wikimedia.org/wikipedia/en/a/a1/Jetty_logo.png?download
Destination: C:\Users\joakim\AppData\Local\Temp\tmp2166600286896937563.dl (11,604 bytes)
Process finished with exit code 0
One (or more) of the following is likely causing your issue.
There is either something wrong with your server, not complying with the HTTP spec.
The HTTP exchange isn't complete yet (from the protocol point of view). Capture the traffic and verify the behavior.
The IOUtil library you are using (you didn't say which one) has a bug.
The fact that wget (or curl) works is likely because they are not strict with Content-Length (per recommendations in RFC7230) and will display / download all content received until physical connection EOF/disconnect. While the HTTP/1.1 protocol has a connection persistence and strict rules on when the request (and response) content ends.

Is possible to call servlet from applet

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!

Rails action not responding to Java POST

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();

Categories