I am confused as to how to send a post request in Java with JSON parameters. I have seen many examples that use HttpPost library which I can not access. Below is my code:
public class endpointtest {
public String endpoint(String urlStr, String username) {
final StringBuilder response = new StringBuilder();
try {
//creating the connection
URL url = new URL(urlStr);
HttpClient client = HttpClient.newHttpClient();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
//builds the post body, adds parameters
final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes(toJSON(globalId));
out.flush();
out.close();
//Reading the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputline;
while ((inputline = in.readLine()) != null) {
response.append(inputline);
}
in.close();
connection.getResponseCode();
connection.disconnect();
} catch (final Exception ex) {
ex.printStackTrace();
System.out.println(" error ");
}
return response.toString();
}
}
class main {
public static void main(String[] args){
endpointtest ep = new endpointtest();
ep.endpoint("localhost:8080/endpoint","""
{
"name": "mike",
"Id": "123"
}
""");
}
}
I am trying to pass the json in the main method (I know I am not doing it right), and was wondering as to how I would do this correctly.
This is the simplest way to do it.
public class Main {
public static void main(String[] args) throws IOException {
String apiUrl = "http://myserver/rest/V1.0/manage/export"; // Your api/http link
String userName = "admin"; // Your username
String password = "adminpro"; // Your password
sendRequest(basicUrl, userName, password);
}
public static void sendRequest(String apiurl,String userName,String password){
try{
URL url = new URL(apiurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes()));
String payload = "{\"sampleKey\":\"sampleValue\"}";// This should be your json body i.e. {"Name" : "Mohsin"}
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
System.out.println(connection.getResponseCode() + " " + connection.getResponseMessage()); // THis is optional
connection.disconnect();
}catch (Exception e){
System.out.println(e);
System.out.println("Failed successfully");
}
}
}
This Question is asked before here:
HTTP POST using JSON in Java
See it and comment this if you face any problem.
I want to login to my spacetrack account in order to download by code some orbital data.
Following the instruction found on the site for java users I test this portion of code:
private static void loginSpaceTrack() {
try {
String baseURL = "https://www.spacetrack.org";
String authPath = "/auth/login";
String userName = "USERNAME";
String password = "PASSWORD";
String query = "/basicspacedata/query/class/tle_latest/ORDINAL/1/EPOCH/%3Enow30/orderby/NORAD_CAT_ID/format/3le";
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL(baseURL + authPath);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
String input = "identity=" + userName + "&password=" + password;
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
}
url = new URL(baseURL + query);
br = new BufferedReader(new InputStreamReader((url.openStream())));
while ((output = br.readLine()) != null) {
}
url = new URL(baseURL + "/ajaxauth/logout");
br = new BufferedReader(new InputStreamReader((url.openStream())));
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
obviously changing USERNAME and PASSWORD with my Account.
At the point: OutputStream os = conn.getOutputStream();
I have an exception: UnknownHostException
Note that at this point I haven't login with my credentials.
Similar issue in android
Someone could help me to fix this problem ?
Thanks all.
Try to change ur baseURL:
String baseURL = "https://www.space-track.org";
I'm working with a RESTFul api in Java EE7. I'm using a #Stateless EJB with a method that I can reach by a HTTP Post request. I am trying to validate a recaptcha code in the server side, so I need to make a HTTP Post request to https://www.google.com/recaptcha/api/siteverify/ with my secret key and the google captcha response that the client sent.
The problem occurs when I try to make the request from the server. The exception is a ConnectException with message "Connection timed out: connect". I think I cannot connect to the web, but I am not sure. I am using NetBeans IDE 8.1
Here is the code:
#Stateless
#Path("sign-in")
public class SignIn
{
#POST
#Produces(MediaType.APPLICATION_JSON)
public javax.ws.rs.core.Response registerUser(String data) throws IOException, JSONException
{
JSONObject JObj = new JSONObject(data);
String gCaptchaResponse = JObj.getString("$captchaResponse");
if (!VerifyGCaptchaResponse(gCaptchaResponse))
{
//Response with error
}
//Logic to "sign-in"
//...
}
private final String urlverificacion = "https://www.google.com/recaptcha/api/siteverify/";
private boolean VerifyGCaptchaResponse(String GCResponse) throws JSONException
{
boolean res = false;
String paramSecret = "secret="+appSettings.getCaptchaSecretKey();
String paramResponse = "response="+GCResponse;
String urlparameters = paramSecret + "&" + paramResponse;
byte[] postData = urlparameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
HttpURLConnection connection = null;
try
{
URL url = new URL(urlverificacion);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty( "charset", "utf-8");
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
//Make request
OutputStream os = connection.getOutputStream(); // <<<<<<===== Here is when the problem occurs!!!
os.write(postData);
os.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Fallo conexion : codigo de error HTTP : " + connection.getResponseCode());
}
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("Respuesta del servicio .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
builder.append(output);
}
String idSicom = "0";
Integer id = 0;
JSONObject jResponse = new JSONObject(builder.toString());
if (jResponse.has("success"))
{
String success = jResponse.getString("success");
res = true;
}
else
{
}
connection.disconnect();
}
catch (java.net.ConnectException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
catch (IOException | RuntimeException | JSONException e)
{
String error = e.getMessage();
String cause = Arrays.toString(e.getStackTrace());
}
finally
{
}
return res;
}
}
I'm having trouble logging into my schools moodle webpage and downloading the source code,
so far i am able to receive the login page it never actually logs in,
any help would be greatly appreciated i have been stuck with this problem for a couple of weeks now.
The code below is a not my own but a modified version of multiple examples that i have found on the web.
import java.net.*;
import java.io.*;
import java.util.*;
public class LoginByHttpPost
{
private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String LOGIN_USER_NAME = "myusername";
private static final String LOGIN_PASSWORD = "mypassword";
private static final String LOGIN_DOMAIN = "students.ltu.edu.au";
private static final String TARGET_URL = "https://www.latrobe.edu.au/lms/login/";
private String page ="";
public static void main (String args[])
{
LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost();
httpUrlBasicAuthentication.httpPostLogin();
}
public void httpPostLogin ()
{
try
{
String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD, LOGIN_DOMAIN);
HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
page = readResponse(urlConnection);
System.out.println("Successfully made the HTPP POST.");
System.out.println("Recevied response is: '/n" + page + "'");
}
catch(IOException ioException)
{
System.out.println("Problems encounterd.");
}
}
private String preparePostContent(String loginUserName, String loginPassword, String loginDomain) throws UnsupportedEncodingException
{
String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
String encodedLoginDomain = URLEncoder.encode(loginDomain, "UTF-8");
String content = URLEncoder.encode("username=", "UTF-8") + encodedLoginUserName
+ URLEncoder.encode("&password=", "UTF-8") + encodedLoginPassword
+ URLEncoder.encode("&domain=", "UTF-8") + encodedLoginDomain
+ URLEncoder.encode("&Login=", "UTF-8") + URLEncoder.encode("Login", "UTF-8");
return content;
}
public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
{
DataOutputStream dataOutputStream = null;
HttpURLConnection conn = null;
String cookieFirst = null;
String cookieValue = null;
String totalCookie = "";
try
{
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URL url = new URL(targetUrl);
conn = (HttpURLConnection)url.openConnection();
conn.getContent();
CookieStore cookiejar = manager.getCookieStore();
List<HttpCookie> cookiesList = cookiejar.getCookies();
for(HttpCookie cookiel: cookiesList)
{
totalCookie += cookiel+"; ";
}
totalCookie = totalCookie.substring(0, totalCookie.length()-1);
System.out.println("Total Cookie: " + totalCookie);
}
catch(Exception e)
{
System.out.println("Something went wrong");
}
HttpURLConnection urlConnection = null;
try{
URL url = new URL(targetUrl);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(true);
urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
urlConnection.setRequestProperty("Content-Length", Integer.toString(content.length()));
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Cookie", totalCookie);
urlConnection.connect();
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
}
catch(IOException ioException)
{
System.out.println("I/O problems while trying to do a HTTP post.");
ioException.printStackTrace();
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch(Throwable ignore)
{
}
}
if (urlConnection != null)
{
urlConnection.disconnect();
}
throw ioException;
}
return urlConnection;
}
private String readResponse(HttpURLConnection urlConnection) throws IOException
{
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String responeLine;
StringBuilder response = new StringBuilder();
while ((responeLine = bufferedReader.readLine()) != null)
{
response.append(responeLine + "\n");
}
return response.toString();
}
catch(IOException ioException)
{
System.out.println("Problems while reading the response");
ioException.printStackTrace();
throw ioException;
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch(Throwable ignore)
{
}
}
}
}
}
To access this web page and log in, you're using a web browser and not a sequance of telnet commands, because it's much easier, right? Then, as a programmer, do the same and use a programmatic web browser rather than a sequence of low-level actions using cookies and URL connections. It will also be much easier.
HtmlUnit is such a programmatic web browser. The end of its Getting started page shows an example of loading a web page and submitting a form. HtmlUnit will handle the submission, cookie handling, encoding, etc. for you.
How do I connect to a remote URL in Java which requires authentication. I'm trying to find a way to modify the following code to be able to programatically provide a username/password so it doesn't throw a 401.
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
There's a native and less intrusive alternative, which works only for your call.
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
You can set the default authenticator for http requests like this:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)
You can also use the following, which does not require using external packages:
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.
Sample URL: http://user:pass#example.com/url
URL url = new URL("http://user:pass#example.com/url");
URLConnection urlConnection = url.openConnection();
if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
InputStream inputStream = urlConnection.getInputStream();
Please note in the comment, from valerybodak, below how it is done in an Android development environment.
As I have came here looking for an Android-Java-Answer I am going to do a short summary:
Use java.net.Authenticator as shown by James van Huis
Use Apache Commons HTTP Client, as in this Answer
Use basic java.net.URLConnection and set the Authentication-Header manually like shown here
If you want to use java.net.URLConnection with Basic Authentication in Android try this code:
URL url = new URL("http://www.example.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc
Was able to set the auth using the HttpsURLConnection
URL myUrl = new URL(httpsURL);
HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//httpsurlconnection
conn.setRequestProperty("Authorization", basicAuth);
few of the changes fetched from this post. and Base64 is from java.util package.
Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.
We found it sniffing packets thanks to Wireshark.
Here is our solution :
import org.apache.commons.codec.binary.Base64;
HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());
private String getBasicAuthenticationEncoding() {
String userPassword = username + ":" + password;
return new String(Base64.encodeBase64(userPassword.getBytes()));
}
Hope it helps!
Use this code for basic authentication.
URL url = new URL(path);
String userPass = "username:password";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.connect();
Since Java 9, you can do this
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setAuthenticator(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("USER", "PASS".toCharArray());
}
});
I'd like to provide an answer for the case that you do not have control over the code that opens the connection. Like I did when using the URLClassLoader to load a jar file from a password protected server.
The Authenticator solution would work but has the drawback that it first tries to reach the server without a password and only after the server asks for a password provides one. That's an unnecessary roundtrip if you already know the server would need a password.
public class MyStreamHandlerFactory implements URLStreamHandlerFactory {
private final ServerInfo serverInfo;
public MyStreamHandlerFactory(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
#Override
public URLStreamHandler createURLStreamHandler(String protocol) {
switch (protocol) {
case "my":
return new MyStreamHandler(serverInfo);
default:
return null;
}
}
}
public class MyStreamHandler extends URLStreamHandler {
private final String encodedCredentials;
public MyStreamHandler(ServerInfo serverInfo) {
String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
}
#Override
protected URLConnection openConnection(URL url) throws IOException {
String authority = url.getAuthority();
String protocol = "http";
URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());
HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
return connection;
}
}
This registers a new protocol my that is replaced by http when credentials are added. So when creating the new URLClassLoader just replace http with my and everything is fine. I know URLClassLoader provides a constructor that takes an URLStreamHandlerFactory but this factory is not used if the URL points to a jar file.
i did that this way you need to do this just copy paste it be happy
HttpURLConnection urlConnection;
String url;
// String data = json;
String result = null;
try {
String username ="user#gmail.com";
String password = "12345678";
String auth =new String(username + ":" + password);
byte[] data1 = auth.getBytes(UTF_8);
String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
//Connect
urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+base64);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
JSONObject obj = new JSONObject();
obj.put("MobileNumber", "+97333746934");
obj.put("EmailAddress", "danish.hussain#example.com");
obj.put("FirstName", "Danish");
obj.put("LastName", "Hussain");
obj.put("Country", "BH");
obj.put("Language", "EN");
String data = obj.toString();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
ANDROD IMPLEMENTATION
A complete method to request data/string response from web service requesting authorization with username and password
public static String getData(String uri, String userName, String userPassword) {
BufferedReader reader = null;
byte[] loginBytes = (userName + ":" + userPassword).getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", loginBuilder.toString());
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null){
sb.append(line);
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}