I understand Java but am completely inexperienced with connecting to web applications. How would I take the following HTTP POST request and make it JSON? The overall purpose is to send information from a Java application to an online Ruby on Rails SQLite3 database.
import java.io.*;
import java.net.*;
public class HTTPPostRequestWithSocket {
public void sendRequest() {
try {
String params = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode("value2", "UTF-8");
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0rn");
wr.write("Content-Length: " + params.length() + "rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close(); // Should this be closed at this point?
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I have an activity where the user enters his / her name, username, and password. I want to send this information as an entry in a MySQL database. Here is my code:
protected String doInBackground(String... params) {
String reg_url = "http://MyIPAddress:ServerPort#/Register.php";
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
return "Registration Success!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The code runs without any errors, but the database remains empty after the program is executed. Here is my PHP file (Register.php):
<?php
require "Connection.php"; //Establishes connection to database
$name = $_POST["user"];
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$sql_query = "insert into user_info values('$name','$user_name','$user_pass');";
if (mysqli_real_query($link, $sql_query)) {
echo "<h1> Data Insertion Success! </h1>";
}
else {
echo "Data Insertion Error...";
}
?>
And the code to connect to the database (Connection.php):
<?php
$link = mysqli_init();
$success = mysqli_real_connect($link,$host,$user,$password,$db,$port);
if($success) {
echo "<h1> Success! </h1>";
}
else {
echo "Error...".mysqli_connect_error();
}
?>
Am I missing something here? I would gladly appreciate your help. Thanks!
Here's the code I ended up using to send the data to my database within the doInBackground method:
try{
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
URL url = new URL(reg_url);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
Log.e("TAG", sb.toString());
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
Reference: Android login to mysql database
Also turned out the port number I had entered for my server was incorrect. I fixed that as well, and now everything seems to work fine. Thank you to all of you guys for the help!
I want the get some data from my database on my android application. This is my code:
try{
String nome = (String)arg0[0];
String stato = (String)arg0[1];
String link="http://www.example.org/AndroidPage.php";
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
data += "&" + URLEncoder.encode("stato", "UTF-8") + "=" + URLEncoder.encode(stato, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("exception: " + e.toString());
}
If I comment the BufferReader statement I don't get any error. Here is the error..
(The file exist in the server)
http://i.stack.imgur.com/mb3sc.png
UPDATE:
I resolved the problem.. The error was inside the php script, I forgot to write a semicolon.
Did you add the Internet permission to the manifest?
<uses-permission android:name="android.permission.INTERNET" />
I am new to Socket Programming.
I have connected to Server from my Client Program,But the response im getting is
Header info + Actual content(what i need ie XML data)
I just want to remove Headers.
This is my Code :
public class TestSocket{
public static void main(String args[]){
try{
URL url = new URL("http://xxxx.de:8080/abcd");
String path=url.getFile();
int port = url.getPort();
String host = url.getHost();
Socket cliSocket = new Socket(host,port);
String req = "yyyy";
req="name="+req;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));
bw.write("POST " + path + " HTTP/1.0\r\n");
bw.write("Host: " + host + "\r\n");
bw.write("Content-Length: " + req.length() + "\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");
bw.write(req);
bw.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));
String line;
System.out.println("Step 4 : Getting Input Stream");
StringBuffer serverData = new StringBuffer("");
while ((line = rd.readLine()) != null) {
serverData.append(line);
}
System.out.println(serverData);
String data = serverData.toString();
int index = data.indexOf("<");
String xmlData =null;
if(index!=-1){
xmlData = data.substring(index);
System.out.println("XML Content :"+xmlData);
}else{
System.out.println("XML Data Not Retrived");
}
bw.close();
rd.close();
}catch(java.net.UnknownHostException uh){
System.out.println("UH : Host Not Found ");
}catch(IOException ioe){
System.out.println("IO Exp "+ioe.getMessage());
}catch(Exception e){
System.out.println("Exp "+e.getMessage());
}
}
}
Response :
HTTP/1.1 200 OKServer: Apache-Coyote/1.1X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA date=200807181417)/JBossWeb-2.0Content-Type: text/xml;charset=UTF-8Content-Length: 1110Date: Wed, 30 Apr 2014 12:13:10 GMTConnection: close
And then XML Data ,
I just only need XML data , Not HTTP/1.1 200 OKServer: Apache-Coyote/1.1X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA .......... etc
Use something like HttpClient form Apache HttpComponents. This save you from most the HTTP stuff and lets you deal directly with the message content.
I have a java servlet class that is performing a GET to a specific URL. I am also passing data as part of the GET.
What I need, is in my HTTP Server code that recieves this data, how do I insert user based response data into the Header back so my calling Java servlet class can read it.
I can read standard response things like .getResponseCode() etc, but I need to insert my own response into the header some how. How can this be done? and how can I read it?
This is my java servlet send class:
public void sendRequest(String data, String sendUrl) throws Throwable{
String messageEncoded = URLEncoder.encode(data, "UTF-8");
String message = URLDecoder.decode(messageEncoded);
System.out.println("messageEncoded : " + messageEncoded);
System.out.println("messageDecoded : " + message);
try {
URL url = new URL(sendUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(message);
writer.close();
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : connection.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Ok
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
System.out.println(this.getClass() + " : MalformedURLException Error occured due to: " + e);
} catch (IOException e) {
System.out.println(this.getClass() + " : IOException Error occured due to: " + e);
}
}
I'm trying to create a Foursquare application using its Java API v2 but I couldn't find any sample source code for the checkin process. I don't need to full source code (authentication, venue search, etc), I just need to checkin part.
Can somebody help me?
import java.net.*;
import java.io.*;
class HelloCheckin {
public static void main(String[] args) {
try {
// Construct data
String data = URLEncoder.encode("ll", "UTF-8") + "=" + URLEncoder.encode("53.576317,0.113386", "UTF-8");
data += "&" + URLEncoder.encode("venueId", "UTF-8") + "=" + URLEncoder.encode("4e144a2cc65bedaeefbb824a", "UTF-8");
data += "&" + URLEncoder.encode("oauth_token", "UTF-8") + "=" + URLEncoder.encode("YOUR_OAUTHTOKEN", "UTF-8");
// Send data
URL url = new URL("https://api.foursquare.com/v2/checkins/add");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
} }
The body of this code came from Simple Java Post