Reputation: 1088
I'm new in using REST call .
I have a test.json
file in my project.
Content of the file is:
{
"Added": {
"type": "K",
"newmem": {
"IDNew": {
"id": "777709",
"type": "LOP"
},
"birthDate": "2000-12-09"
},
"code": "",
"newest": {
"curlNew": "",
"addedForNew": ""
}
}
}
Code in Java :
import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("test.json");
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader(file.getAbsolutePath()));//path to the JSON file.
System.out.println(data.toJSONString());
URL url2 = new URL("myURL");
HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");
conn.setDoOutput(true);
OutputStream outStream = conn.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(data.toJSONString());
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
String response = null;
DataInputStream input = null;
input = new DataInputStream (conn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
Exception: java.io.IOException: Server returned HTTP response code: 401 for URL: https://url_example.com/ at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263) at ab.pkg.TestAuth.main(TestAuth.java:44)
In Soap Ui , Adding the Endpoint and above content as a request body for the POST request is a successful response .
How can I read the json content and pass it as a request body in java ?
Upvotes: 0
Views: 22991
Reputation: 1069
Try:
String username = "username";
String password = "password";
String auth=new StringBuffer(username).append(":").append(password).toString();
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
post.setHeader("AUTHORIZATION", authHeader);
Also, have a look at the answers at this link: Http Basic Authentication in Java using HttpClient?
Upvotes: 0
Reputation: 2111
I admit I read the code fast but it seems ok. However, a 401 status means this server's url requires proper authentication. https://httpstatuses.com/401
You may need to send valid authentication to be authorized. Your authorization header must be invalid.
Upvotes: 1
Reputation: 36
You can read the file in a method and pass the json string data read from the file to another method for posting the json data to the Rest end point
1) Read the Json data from the file
public String readJsonDataFromFile() {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(new
File("sample.json")));
StringWriter writer = new StringWriter();
IOUtils.copy(inputStreamReader, writer);
return writer.toString());
}
2) Call the Restend point passing the Json data
public void postData(String payload) {
String url = "http://localhost:8080/endPoint";
// Use the access token for authentication
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url,
HttpMethod.POST, entity, String.class);
System.out.println(response.getBody());
}
As the response returned is 401, it is not successfully authenticated with the rest endpoint, check the error log if it gives more info about the error like whether the access token is expired.
Upvotes: 0
Reputation: 326
I recommend you to parse JSON file to String from this topic: How to read json file into java with simple JSON library
Then you can take your JSON-String and parse to Map (or whatever you specify) by popular and simple library Gson
.
String myJSON = parseFileToString(); //get your parsed json as string
Type mapType = new TypeToken<Map<String, String>>(){}.getType(); //specify type of
your JSON format
Map<String, String> = new Gson().fromJson(myJSON, mapType); //convert it to map
Then you can pass this map as a request body to your post. Dont pass any JSON data as URL in POST methods. Data in URL isn't good idea as long as you are not using GET (for example).
You can also send whole JSON (in String version) as parameter, without converting it to Maps or objects. This is only example :)
And if you want to pass this map in your POST method you can follow this topic: Send data in Request body using HttpURLConnection
[UPDATE] it worked fine, result 200 OK from server, no exceptions, no errors:
package com.company;
import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("test.json");
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader(file.getAbsolutePath()));//path to the JSON file.
System.out.println(data.toJSONString());
String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
URL url2 = new URL("https://0c193bc3-8439-46a2-a64b-4ce39f60b382.mock.pstmn.io");
HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");
conn.setDoOutput(true);
OutputStream outStream = conn.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(data.toJSONString());
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
String response = null;
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
DataInputStream input = null;
input = new DataInputStream (conn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
Let me know if that answer fixed your problem. Greetings!
Upvotes: 4
Reputation: 612
If you want to read the content of the JSON file, you can do something like this, assuming your JSON file is located in the same package as the class that tries to load it:
InputStream stream = YourClass.class.getResourceAsStream(fileName);
String result = CharStreams.toString(new InputStreamReader(stream));
As for sending the actual request, I think you can have a look at How to send Https Post request in java for instance
Upvotes: -1