Java HTTP Request for PHP - java

So i am trying to send some variables to my localhost which runs a php file which should output the variable.
URL url = null;
try {
String charset = "UTF-8";
String MontagMittagVorspeise = "value1";
String query = String.format("param1=%s", URLEncoder.encode(MontagMittagVorspeise, charset));
url = new URL("127.0.0.1/Haunsbot/Hauns.php");
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And this is my PHP:
<?php
if(isset($_GET["MontagMittagVorspeise"]))
{echo "Vehicle :".$_GET["MontagMittagVorspeise"];}
?>
And IntelliJ gives me the following error: java.net.MalformedURLException: no protocol: 127.0.0.1/Haunsbot/Hauns.php
Can someone help me?:)

Related

send SMS using java spring mvc not working

I am working one web application spring MVC.i want to send sms using web.
I tried below code.
If i run single java file using main() then its working and when i tried it through web its not working.
Can anybody help me to solve this.
Below is my code
public static String doSendSMS(String url_str) {
StringBuffer response = new StringBuffer();
try {
URL obj = new URL(url_str);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url_str);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
}
return response.toString();
}
Below is working code.
public class sms {
private static String sessionCookie;
public static String loginSMS(String userName, String password,String url) {
String cookie = null;
URL urlLogin;
String loginContent;
HttpURLConnection loginConnection;
try {
//UTF-8 encoding is the web standard so data must be encoded to UTF-8
userName = URLEncoder.encode(userName, "UTF-8");
password = URLEncoder.encode(password, "UTF-8");
urlLogin = new URL(url);
loginConnection = (HttpURLConnection) urlLogin.openConnection();
loginContent = "username=" + userName + "&password=" + password;
loginConnection.setDoOutput(true);
loginConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
loginConnection.setRequestProperty("Content-Length", String.valueOf(loginContent.length()));
loginConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
loginConnection.setRequestProperty("Accept", "*/*");
loginConnection.setRequestProperty("Referer", url);
loginConnection.setRequestMethod("POST");
loginConnection.setInstanceFollowRedirects(false);
//Writing the Content to the site
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(loginConnection.getOutputStream()), true);
printWriter.print(loginContent);
printWriter.flush();
printWriter.close();
//Reading the cookie
cookie = loginConnection.getHeaderField("Set-Cookie");
} catch (MalformedURLException ex) {
System.err.println("Login URL Error");
} catch (UnsupportedEncodingException ex) {
System.err.println("Error in encoding Username or Password");
} catch (IOException ex) {
System.err.println("Can not connect to Login URL");
}
if (cookie == null || cookie.isEmpty()) {
System.err.println("Some error occured...Try again in a few seconds..If still problem exists check your username and password");
}
sessionCookie = cookie;
return cookie;
}
public static void sendSMS( String action,String urlString,String content) {
loginSMS("user", "user123","url");
URL sendURL;
HttpURLConnection sendConnection;
String sendContent;
try {
sendURL = new URL(urlString);
sendConnection = (HttpURLConnection) sendURL.openConnection();
// sendContent="custid=undefined&HiddenAction=instantsms&Action="+action+"&login=&pass=&MobNo="+ phoneNumber+ "&textArea="+message;
sendContent = content;
sendConnection.setDoOutput(true);
sendConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
sendConnection.setRequestProperty("Content-Length", String.valueOf(sendContent.getBytes().length));
sendConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
sendConnection.setRequestProperty("Accept", "*/*");
sendConnection.setRequestProperty("Cookie", sessionCookie);
sendConnection.setRequestMethod("POST");
sendConnection.setInstanceFollowRedirects(false);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(sendConnection.getOutputStream()), true);
printWriter.print(sendContent);
printWriter.flush();
printWriter.close();
//Reading the returned web page to analyse whether the operation was sucessfull
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sendConnection.getInputStream()));
StringBuilder SendResult = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
SendResult.append(line);
SendResult.append('\n');
//Message has been submitted successfully
}
System.out.println("Responce : " + SendResult);
bufferedReader.close();
logoutSMS();
} catch (UnsupportedEncodingException ex) {
System.err.println("Message content encoding error");
// System.exit(0);
} catch (MalformedURLException ex) {
System.err.println("Sending URL Error");
// System.exit(0);
} catch (IOException ex) {
System.err.println("Sending URL Connection Error");
ex.printStackTrace();
// System.exit(0);
}
}
}

Https connection Android with Http authentication

I want to make a HTTPS connection with a webservice in Android Studio but it doesn't work with the code that I have written. I get a FileNotFound Exception.
My URL is working in the browser.
And response code is 400.
This is my code:
protected Void doInBackground(String... params) {
String https_url = "HERE MY HTTPS URL";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userPassword = "USERNAME" + ":" + "PASSWORD";
String encoding = new String(Base64.encode(userPassword.getBytes(), Base64.DEFAULT));
con.setRequestProperty("Authorization", "Basic " + encoding);
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
//dumpl all cert info
print_https_cert(con);
//dump all the content
print_content(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Someone who can help me out?

Coverting java request to c#

I am trying to convert this request written java to c#(Xamarin android) , java one seems to be working , but c# one is failing with bad request(400) .
Could you please point out if i am translating rightly ?
Java code
String url = "https://someUrl";
try {
URL url1 = new URL(url);
URLConnection uc = url1.openConnection();
String basicAuth = Base64.encodeToString((APIKEY).getBytes("UTF-8"), Base64.NO_WRAP);
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
// Log.e(TAG, "response: " + response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
C# code
String url = "https://someUrl";
// Add custom implementation here as needed.
var uri = new Uri(url);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes (API_KEY), Base64FormattingOptions.None);
try
{
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", authHeaderValue);
var response = await client.GetAsync(uri);
}
}
catch (Exception e)
{
Log.Debug ("TokenSending", "failed to send token" + e);
}

Using Java (HttpURLConnection) to authenticate to Restheart (for Mongodb)

I am using restheart to provide a restful interface to mongodb. The interface is set up and running and provides the correct answer if a GET request is sent through Chrome. However if I use the following java code using a HttpURLConnection I get a 201 response with no content.
try {
videos = new URL("http://www.example.com:8080/myflix/videos");
} catch (Exception et) {
System.out.println("Videos URL is broken");
return null;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) videos.openConnection();
String login="admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic "+encoded);
hc.setDoInput(true);
hc.setDoOutput(true);
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Content-Type", "application/json");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
return (null);
}
BufferedReader br = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(
hc.getOutputStream());
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
String inputLine;
String sJSON = null;
try {
int rc = hc.getResponseCode();
What is the correct way to authenticate using Java to the resthert interface? (Details on the restheart authentication is here Restheart authentication
I made few changes (look for inline comments starting with <==) and it works:
The way you generate the authentication request header is correct. When I run your code I actually got 415 Unsupported Media Type, that went away commenting out hc.setDoOutput(true). A GET is a input operation, in fact you were also trying to get an OutStream from the connection: you need to get an InputStream actually.
URL url;
try {
url = new URL("http://127.0.0.1:8080/test/huge");
} catch (Exception et) {
System.out.println("Videos URL is broken");
Assert.fail(et.getMessage());
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
hc.setDoInput(true);
//hc.setDoOutput(true); <== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(hc.getInputStream()); // <== the request is a GET, data is in input
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
Assert.assertEquals(200, rc);

Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function

I have a string that I am trying to send to a Parse.com cloud function. According to the REST API documentation (https://www.parse.com/docs/rest#general-requests), it must be in json format, so I made it into a json object and converted it to a string to append to the end of the http request url.
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
String urlParameters = jsonParam.toString();
Then I send the request as so, in my attempt to match their cURL code example as Java code:
con.setDoOutput(true);
DataOutputStream wr = null;
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Nonetheless, I receive a returned error code of 400 with error message "Bad Request", which I believe to be caused by unrecognizable parameters being sent to the cloud function. None of the other errors in my code trigger. Yet I verified through console logs that emailId is a normal string and the resulting JSON object, as well as its .toString() equivalent comes out as a proper string reading of a JSON object. Also this worked for another function I have in which I am creating an object in my Parse database. So why would it not work here?
Here is the full function for reference and context:
private void sendEmailWithParse(String emailId) throws IOException {
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
System.out.println("Failed to connect to http link");
e.printStackTrace();
}
//add request header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
System.out.println("Failed to set to POST");
e.printStackTrace();
}
con.setRequestProperty("X-Parse-Application-Id", "**************************************");
con.setRequestProperty("X-Parse-REST-API-Key", "************************************************");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
System.out.println("parameter being sent to cloud function: " + jsonParam);
System.out.println("parameter being sent to cloud function as string: " + jsonParam.toString());
String urlParameters = jsonParam.toString();
// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch (IOException e1) {
System.out.println("Failed to get output stream");
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch (IOException e) {
System.out.println("Failed to connect to send over Parse object as parameter");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
System.out.println("Failed to connect to close datastream connection");
e.printStackTrace();
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
System.out.println("Failed to connect to get response code");
e.printStackTrace();
}
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response message: " + con.getResponseMessage());
}
I solved the problem by using the HttpRequest external library. It gave me better control of the request and made for easier debugging of the problem. The server was receiving the request just fine, the problem was with the JSON encoding. Rather than putting the JSON object as a parameter in the request, I inserted it into the body of the http request and encoded it in UTF-8.
In the end, this is the code that worked:
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
//Attempt to use HttpRequest to send post request to parse cloud
HttpRequest request = HttpRequest.post(obj).contentType("application/json");
request.header("X-Parse-Application-Id", "**************************");
request.header("X-Parse-REST-API-Key", "********************");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
request.send(jsonParam.toString().getBytes("UTF8"));
if (request.ok())
System.out.println("HttpRequest WORKED");
else
System.out.println("HttpRequest FAILED " + request.code() + request.body());

Categories

Resources