Does Java URLConnection send Metadata? - java

when you open a connection via URLConnection to read the content of a Webpage,
try {
URL url = new URL("https://stackoverflow.com/questions/46939965/does-java-urlconnection-send-metadata");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
}catch(IOException e) {
e.printStackTrace();
}
what will Java leave for Information?
Will statistical data like the Webbrowser saved? Will that be the "Java"?
Thx for help,
~Corn

HTTP "metadata" is normally sent in the headers. The one that would indicate the web browser is typically called "USER_AGENT." I do not believe Java will populate these headers for you implicitly.

Related

OutputStream os = con.getOutputStream() throws NullPointerException

I am trying to build an android app for a website and I need to post some value to this page first.
Here is my code:
private void sendPOST(String user,String pass) throws IOException {
String POST_PARAMS = "username="+user+"&password="+pass;
URL obj = new URL("http://xx.xx.xx.xx/mysite/test.php");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
//----------------------------------------------------------- For POST only - START---------------------------------------------
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// ------------------------------------------------------------For POST only - END----------------------------------------------------
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Toast.makeText(getApplicationContext(), response.toString()==""?"No Result":response.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"POST request failed", Toast.LENGTH_LONG).show();
}
}
when this line is executed OutputStream os = con.getOutputStream();
a null exception occurs.
I am unable to proceed further. Please suggest what i must do to remove this exception.
put your delevelopment server in another locatation other than localhost (try using the real IP, something like: 192.168.0.1).
sometimes you will receive a successfull connection from HttpUrlConnection.openConnection() (it returns non null object) and this not guarantee the subsequents calls to success. In other words, when you call con.getOutputStream() it throws an exception no matter if con is non-null.
It's the old question but I might have to answer on it because I have face to it today. When you ping http (instead https) have to put in manifest -> application: android:usesCleartextTraffic="true"
I think this would helped you years ago...
try(OutputStream os = con.getOutputStream()) {
byte[] input = POST_PARAMS.getBytes("utf-8");
os.write(input, 0, input.length);
}
maybe you should try to "connect" first before doing anything with your created HttpURLConnection con.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.connect();
do more stuff with con...
I hope this helps you :)
URL obj = new URL("http://xx.xx.xx.xx/mysite/test.php");
URL Class object "obj" can't reach to your mentioned URL properly.
Try this instead:
URL obj = new URL("http://"+"xx.xx.xx.xx/mysite/test.php");

how to do an online xml request in java to a url that require authentication

I want to do an online xml request in java but the server responds with 401 error that means that there is an authentication that is need to access the server. I have the certfile.cer that i can use to do the authentication but i dont know how to load it in java.How can I achieve this in java? Here is part of my code.
StringBuilder answer = new StringBuilder();
URL url = new URL("www.myurl.com");
URLConnection conn = url.openConnection();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
String line;
while ((line = reader.readLine()) != null)
{
answer.append(line);
}

HTML Form Action Java

I have a java program which I want to input something into an html form. If possible it could just load a url like this
.../html_form_action.asp?kill=Kill+Server
But i'm not sure how to load a url in Java. How would I do this? Or is there a better way to send an action to an html form?
Depending on your security, you can make an HTTP call in Java. It is often referred to as a RESTFul call. The HttpURLConnection class offers encapsulation for basic GET/POST requests. There is also an HttpClient from Apache.
Here's how you can use URLConnection to send a simple HTTP request.
URL url = new URL(url + "?" + query);
// set connection properties
URLConnection connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.connect(); // send request
// read response
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close(); // close connection

Send POST data from JSP page to remote PHP server (and get an answer)

I'm trying to send some data from a JSP page to a PHP one (which should execute some code and return a success message).
I'm using this java function to make some tests:
public String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
String urlParameters =
"var=" + URLEncoder.encode("varcontent", "UTF-8");
out.println(excutePost("remoteurl",urlParameters));
Now if i run the page i get the response "null" and none of the code in the php page is executed.
Am I doing something wrong? How can I allow the php page to run the code in it?
Isn't a simple echo $_POST['var'] enough to send the data back to the jsp page?
EDIT: I tried to see if the php page is receiving something by writing the posted variable in a file. But nothing is written in it.
$file = 'debug.txt';
echo file_put_contents($file, $_POST['var']);
and here is the exception i'm getting..
java.net.SocketException: Connection reset
No, an echo is not enough. Put $_POST['var'] in say a text file and serve the updated text file (Edit the text file each time you need to keep track of $_POST['var']). Alternatively you can put it in some DB and check for changes.

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());
}

Categories