Unable to use GET Method - java

I am trying to write a code which will give me the contents of the page as the response in a string using GET method in java.
Below is the code I am using, its throwing me error that java.net.MalformedURLException: no protocol
If I try inserting http:// in starting of the URL its giving me Unknown Host Exception.
String request = ("http://gotoanswer.com/?q=What+is+the+Java+equivalent+for+the+following+in+curl%3F");
System.out.println(request);
URL url = null;
try{
new URL(request);
HttpURLConnection connection = (HttpURLConnection) new URL(request).openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
}
catch(IOException e){
System.out.println(e);
}

Related

Java Post Connection Using Try with Resources

I want to implement the code for handling POST requests using try with resources.
Following is my code:
public static String sendPostRequestDummy(String url, String queryString) {
log.info("Sending 'POST' request to URL : " + url);
log.info("Data : " + queryString);
BufferedReader in = null;
HttpURLConnection con = null;
StringBuilder response = new StringBuilder();
try{
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(queryString);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
log.info("Response Code : " + responseCode);
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch(Exception e){
log.error(e.getMessage(), e);
log.error("Error during posting request");
}
finally{
closeConnectionNoException(in,con);
}
return response.toString();
}
I have the following concerns for the code:
How to introduce conditional statements in try with resources for the above scenario?
Is there a way to pass on the connection in try with resources? (It can be done using nested try-catch blocks since URL and HTTPConnection is not AutoCloseable, which itself is not a compliant solution)
Is using try with resources for the above problem is a better approach?
Try this.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable conc = () -> con.disconnect()) {
// add request headers
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(queryString);
}
int responseCode = con.getResponseCode();
try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
// receive response
}
}
() -> con.disconnect() is a lambda expression which execute con.disconnect() at finally stage of the try statement.
1: You can use conditional statements inside try with resources statement also. Unfortunately you have to define new variable for this block and cannot use a predefined variable. ( variable in in your code)
try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) {
// your code for getting string data
}
2: I'm not sure HttpUrlConnection is AutoCloseable, So it might be a good idea to call the disconnect() yourself. I'm open to any suggestion on this one.
3: try with resources will definitely help you in managing the resources. But if you're confident that you're releasing the resources properly after use, then your code is fine.

HttpURLConnection returned different result on Android 5.1 and 4.4 while passing the same params

public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = "";
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Above code worked well on Android 5.1 and Android 6.0, and it returned correct result that I want. But when I ran these on Android 4.4, using the same params, it returned different result. I have tried several times, and attached debugger to the process. I found that the connection could be built successfully, and the ResponseCode was also 200.
I guess there must be something wrong with the HttpURLConnection params, so that the server returned different result. Did I set the params in a way that could work on Android 5.1 and 6.0 but not on 4.4? Can anybody tell me where did I do wrong?
Try below code:
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
.........
}
It works for me. Hope it will work.

Does threading work, when external applications block each other?

I have two raspberry pi´s uploading content to a webpage from the same router, which occasionally makes them block access for each other. To prevent this in java, you would normally use threads and synchronize, wait/notify and all that - but how can you do that, when the applications don´t know about each others excistens? -
My code looks something like that - and works otherwise as expected.
public void sendStrings(String output) {
String url2 = "http://myhomepage.com";
HttpURLConnection connection = null;
try {
URL obj = new URL(url2);
connection = (HttpURLConnection) obj.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(output);
writer.flush();
writer.close();
InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String otherLine;
int responseCode = connection.getResponseCode();
}
catch (IOException e) {
} finally {
connection.disconnect();
}
}

Android Post request not posting any data on server

=====Updated========
Actually below code is fine, My problem is at server side.
=====Updated========
Below is my code,I am using HttpURLConnection but not able to send JSON data to server.
Please help me Thanks in advance
JSONObject jo = new JSONObject();
jo.put("ID", "25")
Log.e("test", jo.toString());
url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(jo.toString());
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
line = sb.toString();
Log.e("json_temp", line);
rd.close();
Your code is fine, it doesn't show a blank array, but a string "Array()". I tried a resource test, and that's exactly what it showed me.
If you type in the URL in the browser, you should see the same thing.

Intercepting json in https(not http) with a python cgi script

I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?

Categories

Resources