How do I use GET method with sending json data in android? - java

API route in Python (Flask)
#app.route('/secret')
def secret():
if request.get_json(force=True)['key'] == 'secret key':
return jsonify(msg='Hello!')
It is working linux terminal
curl -iX GET -d '{"key":"secret key"}' localhost
Linux terminal output this
{"msg":"Hello!"}
It doesn't need to work in browser.
try{
HttpURLConnection connection = (HttpURLConnection)
new URL("http://<my local ip>/secret").openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
JSONObject jsonInput = new JSONObject();
jsonInput.put("key", "secret key");
OutputStream os = connection.getOutputStream();
byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
os.flush();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
} catch (IOException | JSONException e) {
Log.e("MainActivity", "Error: " + e.getMessage());
}
Although the GET method is set to the connection request in my codes, a POST request is being sent to the Python server.
Python Interpreter
Is it impossible to fix this?

Request Body is not recommended in HTTP GET requests. See HERE
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
When you try to write on a URL, you are implicitly POSTing on it despite you had set GET as the HTTP method. At below lines:
OutputStream os = connection.getOutputStream();
byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
For confirmation of my words see Writing to a URLConnection
writing to a URL is often called posting to a URL. The server
recognizes the POST request and reads the data sent from the client.

Related

Getting JSON response as part of Rest call in Java

I am trying to make Rest service call in Java. I am new to web and Rest service. I have Rest service which returns JSON as response. I have the following code but I think it's incomplete because I don't know how to process output using JSON.
public static void main(String[] args) {
try {
URL url = new URL("http://example.com:7000/test/db-api/processor");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/json");
OutputStream os = connection.getOutputStream();
//how do I get json object and print it as string
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
I am new to Rest services and JSON.
Since this is a PUT request you're missing a few things here:
OutputStream os = conn.getOutputStream();
os.write(input.getBytes()); // The input you need to pass to the webservice
os.flush();
...
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream()))); // Getting the response from the webservice
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output); // Instead of this, you could append all your response to a StringBuffer and use `toString()` to get the entire JSON response as a String.
// This string json response can be parsed using any json library. Eg. GSON from Google.
}
Have a look at this to have a more clear idea on hitting webservices.
Your code is mostly correct, but there is mistake about OutputStream.
As R.J said OutputStream is needed to pass request body to the server.
If your rest service doesn't required any body you don't need to use this one.
For reading the server response you need use InputStream(R.J also show you example) like that:
try (InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
byte[] buf = new byte[512];
int read = -1;
while ((read = inputStream.read(buf)) > 0) {
byteArrayOutputStream.write(buf, 0, read);
}
System.out.println(new String(byteArrayOutputStream.toByteArray()));
}
This way is good if you don't want to depends on third-part libraries. So I recommend you to take a look on Jersey - very nice library with huge amount of very useful feature.
Client client = JerseyClientBuilder.newBuilder().build();
Response response = client.target("http://host:port").
path("test").path("db-api").path("processor").path("packages").
request().accept(MediaType.APPLICATION_JSON_TYPE).buildGet().invoke();
System.out.println(response.readEntity(String.class));
Since your Content-Type is application/json, you could directly cast the response to a JSON object for example
JSONObject recvObj = new JSONObject(response);
JsonKey jsonkey = objectMapper.readValue(new URL("http://echo.jsontest.com/key/value/one/two"), JsonKey.class);
System.out.println("jsonkey.getOne() : "+jsonkey.getOne())

error while sending data from java code to PHP in localhost using HTTPPost request

This is my java code to send data through HTTPPost request:
import java.io.*;
import java.net.*;
class HttpURLConnectionEx{
public static void main(String[] args) throws Exception{
URL targetURL = new URL("http://localhost/JAVA/post.php");
HttpURLConnection conn =(HttpURLConnection) targetURL.openConnection();
String body= "fName="+ URLEncoder.encode("value1","UTF-8")+"&lName=" + URLEncoder.encode("value2","UTF-8");
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "UTF-8");
conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
try
{
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(body);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = rd.readLine()) != null) {
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This is my PHP code present in localhost:
<?php
$data = $_POST["fName"];
$dbc = mysqli_connect('localhost','root','root123','JAVA')
or die("error connecting to mysql server");
$query = "INSERT INTO insert_table(data) VALUES('".$data."')";
if($query){
echo "data inserted sucessfully";
}
$result = mysqli_query($dbc,$query) or die("error querying database");
?>
This is the output i 'm getting when i run it in commandline:
A flush after the write is required.
out.flush();
edit
Undefined index: fName
The php error is clear enough, isn't? The $_POST array doesn't contain your POST variables.
First I've checked on php side the content of the post with var_dump($_POST) and:
/* save the raw post to a file */
file_put_contents('/tmp/post.txt', file_get_contents('php://input'));
Both were empty, so I used wireshark to check the HTTP/POST content, it was done but with Content-Length: 0 and without body.
Few googles to something similar to your code and I noticed the flush that mean OutputStreamWriter is buffered and at the time of the post request the output could be not written (sent to the server) or only partially, a good reason for zero content-length.
At this point I think you don't need to use conn.setRequestProperty for "Content-Length", it should be updated according with your buffer content length.

Java IOException "Unexpected end of file from server" when posting large data

I am trying to post XML data to a server which processes this XML and gives a response back, some times the XML data can be very large and the server takes a while to process it, in those cases i fail to get any response back instead i receive a IOException with the message "Unexpected end of file from server". I am positive the XML being sent to the server is not full of errors, is there anything i can do on my end to make sure this doesn't happen or is this a server side issue? Below is code fragment of the method i call to post the data.
Thanks.
String encodedData="some XML"
String urlString="example.com"
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", contentType);
urlConnection.setRequestProperty("Content-Length", encodedData.length()+"");
OutputStream os = urlConnection.getOutputStream();
os.write(encodedData.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
logger.debug("MalformedURLException " + e.getMessage());
logger.debug((new StringBuilder()).append("urlString=").append(urlString).toString());
throw (e);
} catch (IOException e) {
logger.debug("IOException " + e.getMessage());
logger.debug((new StringBuilder()).append("urlString=").append(urlString).toString());
throw (e);
}
return sb.toString();
Not much could be done from the client side, it's just a server side issue in which the server takes very long to process the data which results in the servers connection to timeout before it could send a response.

how to make http get request in Android

I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1&param2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}

send http request to linux server

I have to send an HTTP request to our C programme which is running on a Linux machine. How can I send an HTTP request in Java to our server which is in C and running on a Linux machine?
public void sendPostRequest() {
//Build parameter string
String data = "width=50&height=100";
try {
// Send the request
URL url = new URL("http://www.somesite.com");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//write parameters
writer.write(data);
writer.flush();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
//Output the response
System.out.println(answer.toString());
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
The above example is for sending a POST request using a URL.
If you're asking how to send an HTTP request in Java to a web server written in C, you can use the URLConnection class.
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close(); } catch (Exception e) { }
The above example is for sending a POST request using a URL.
Also take a look at Sun Tutorial on reading/Writing from/to a URLConnection. The other option is to use Apache HTTPComponents which has examples for the HttpCore and HttpClient module.
If you are looking into implementing the web Server, you will have to handle the Http request yourselves which involves a thread pool, parsing the requests, generating HTML, security, multiple sessions, etc or follow the easy route by using off-the-shelf web server like Apache and seeing which all high-level languages like Perl, Ruby can be used for developing the web application.
For implementing your own Http server, please take a look at Micro-Httpd or tinyHttpd
You may also want to look at Adding Web Interface -C++ application which has a sample code.
From the way your question is worded.. I think you need to know some basic stuff before you can start. Try try googling for a simple guide to how web servers work.
Once you have the basic idea, there are a couple of options for a C programmer:
1) You want your C program to be running continuously, waiting for a request from your Java.
In this case, you will have to code your C program to open a Socket and Listen for connections. See http://www.linuxhowtos.org/C_C++/socket.htm for example.
OR
2) You have a web Server on your server which will run your C program each time a particular request is made? In this case, you will have to code your C as a CGI program. See http://www.cs.tut.fi/~jkorpela/forms/cgic.html for example.
Hint: (2) is much easier!

Categories