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())
Related
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.
I have a Spring Boot app built with Maven. Now, I plan to make requests to the SOAP service from this app. SOAP service is defined by WSDL. I am able to make requests and get responses with this method:
private String makeSoapRequest(String request, String action) throws IOException {
URL url = new URL("http://localhost/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
InputStream is = new ByteArrayInputStream(request.getBytes());
baos = new ByteArrayOutputStream();
copy(is, baos);
is.close();
byte[] bytes = baos.toByteArray();
httpURLConnection.setRequestProperty("Content-Length", String.valueOf( bytes.length ) );
httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpURLConnection.setRequestProperty("SOAPAction", action);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream out = httpURLConnection.getOutputStream();
out.write(bytes);
out.close();
InputStreamReader isr = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
ab.append(inputLine);
}
return sb.ToString();
}
However, my request and response here are XML strings. How can I generate my request and response classes from WSDL, so I can use them to make requests with HttpURLConnection?
Using Apache CXF did not help, as I should use HttpURLConnection. It is one of the requirements of the consumed service.
I can generate classes with JAXB or JAX-WS, but sending generated appropriate classes as request body gave me 400 Bad Request error.
You should use a code generator. You can find more information on WSDL2Java in the CXF documentation: https://cxf.apache.org/docs/how-do-i-develop-a-client.html
I'm sending data to an API from Java using POST.
What I'm trying to do is send a particular variable to the API in the POST request, and then use the value of it. But currently the value is empty. The API is definitely being called.
My Java looks like this:
String line;
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL("https://www.x.com/api.php");
String payload = "{\"variable1\":\"value1\",\"variable2\":\"value2\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
This is based on: How to send Request payload to REST API in java?
Currently the value isn't being read correctly. Am I sending it correctly in Java? Do I have to do something to decode it?
The $_POST variable is not set for all HTTP POST requests, but only for specific types, e.g application/x-www-form-urlencoded.
Since you are posting a request containing JSON entity (application/json), you need to access it as follows.
$json = file_get_contents('php://input');
$entity= json_decode($json, TRUE);
You can try to use the following code instead of your String variable payload:
List<NameValuePair> payload = new ArrayList<NameValuePair>();
payload.add(new BasicNameValuePair("variable1", "value1");
That worked for me
When using this code below to make a get request:
private String get(String inurl, Map headers, boolean followredirects) throws MalformedURLException, IOException {
URL url = new URL(inurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(followredirects);
// Add headers to request.
Iterator entries = headers.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
connection.addRequestProperty((String)key, (String)value);
}
// Attempt to parse
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
BufferedReader br = new BufferedReader(isReader );
System.out.println(br.readLine());
// Disconnect
connection.disconnect();
return connection.getHeaderField("Location");
}
The resulting response is completely nonsensical (e.g ���:ks�6��9�rђ� e��u�n�qש�v���"uI*�W��s)
However I can see in Wireshark that the response is HTML/XML and nothing like the string above. I've tried a myriad of different methods for parsing the InputStream but I get the same result each time.
Please note: this only happens when it's HTML/XML, plain HTML works.
Why is the response coming back in this format?
Thanks in advance!
=== SOLVED ===
Gah, got it!
The server is compressing the response when it contains XML, so I needed to use GZIPInputStream instead of InputSream.
GZIPInputStream stream = new GZIPInputStream(connection.getInputStream());
Thanks anyway!
use an UTF-8 encoding in input stream like below
InputStreamReader isReader = new InputStreamReader(stream, "UTF-8");
conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.connect();
int code = conn.getResponseCode();
I have successfully established a connection. I am trying to pass the information over the internet.When the url is opened via browser I am getting response as
{"status":"0","responseCode":"1001","response":"Wrong Settings."}
For correct status is returned as 1.
Is there any method where I can get the status only.I have been trying the following methods but every time I am getting code (below is code snippet) as -1 irrespect of status code when I am verifying manually via browser
This is a JSON text. You will need to use a JSON library.
int code = conn.getResponseCode();
this method returns http status code, for http status codes see
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
while the response code you want to retrieve is actually the response string returned by the server.
To read this use:
try {
InputStream in = new BufferedInputStream(conn.getInputStream());
readStream(in);//method to read characters from stream.
finally {
urlConnection.disconnect();
}
}
You can add below code for get Response string from your connection.
OutputStream connectionOutput = null;
connectionOutput=connection.getOutputStream();
connectionOutput.write(requestJson.toString().getBytes());
connectionOutput.flush();
connectionOutput.close();
inputStream = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream dataCache = new ByteArrayOutputStream();
// Fully read data
byte[] buff = new byte[1024];
int len;
while ((len = inputStream.read(buff)) >= 0) {
dataCache.write(buff, 0, len);
}
// Close streams
dataCache.close();
Now get Response string of json like below.
String jsonString = new String(dataCache.toByteArray()).trim();
JSONObject mJsonobject=new JSONObject(jsonString);
You can now parse your key from this mJsonobject Object.