HTTP POST request with JSON object as data - java

I am struggling to make an HTTP POST request with JSON object as data.
As you can see below, first I created an HTTP Post request. Then I commented out part of it and attempted to modify it in order to add JSON related code. One of the things that confused me was that despite seeing a number of tutorials using the import "org.json.simple.JSONObject" my IDE reads an error message and states "the import org.json.simple.JSONObject cannot be resolved".
Any advice about how to make this code work would be much appreciated.
import java.io.*;
import java.net.*;
import org.json.simple.JSONObject;
public class HTTPPostRequestWithSocket {
public void sendRequest(){
try {
JSONObject obj = new JSONObject();
obj.put("instructorName", "Smith");
obj.put("courseName", "Biology 101");
obj.put("studentName1", "John Doe");
obj.put("studentNumber", new Integer(100));
obj.put("assignment1", "Test 1");
obj.put("gradeAssignment1", new Double("95.3"));
/*
//Note that this code was taken out in order to attempt to send
//the information in the form of JSON.
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: "+obj.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(obj);
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();}
}
}

The reason your IDE says it cannot resolve the import org.json.simple.JSONObject is because the org.json.simple.* packages and classes are not included in Java, but rather belong to the JSON Simple library.

I think that uses Socket is not a good idea. You can better use:
http://hc.apache.org/httpcomponents-client-ga/ (A HTTP Client)
or a java.net.URLConnection. Example:
http://crunchify.com/create-very-simple-jersey-rest-service-and-send-json-data-from-java-client/

You need the jar with the org.json.simple.JSONObject implementation:
http://www.java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm

Related

Java client POST to php script - empty $_POST

I have researched extensively and cannot find a solution. I have been using the solutions provided to other users and it does not seem to work for me.
My java code:
public class Post {
public static void main(String[] args) {
String name = "Bobby";
String address = "123 Main St., Queens, NY";
String phone = "4445556666";
String data = "";
try {
// POST as urlencoded is basically key-value pairs
// create key=value&key=value.... pairs
data += "name=" + URLEncoder.encode(name, "UTF-8");
data += "&address=" +
URLEncoder.encode(address, "UTF-8");
data += "&phone=" +
URLEncoder.encode(phone, "UTF-8");
// convert string to byte array, as it should be sent
byte[] dataBytes = data.toString().getBytes("UTF-8");
// open a connection to the site
URL url = new URL("http://xx.xx.xx.xxx/yyy.php");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
// tell the server this is POST & the format of the data.
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(dataBytes.length);
conn.getOutputStream().write(dataBytes);
conn.getInputStream();
// Print out the echo statements from the php script
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null)
System.out.println(line);
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
and the php
<?php
echo $_POST["name"];
?>
The output I receive is an empty line. I tested to see if it was a php/server side issue by making an html form that sends data over to a similar script and prints the data on the screen and that worked. But, for the life of me, I cannot get this to work with a remote client.
I am using Ubuntu server and Apache.
Thank you in advance.
The problem is actually in what you read as output. You are doing two requests:
1)conn.getInputStream(); - sends POST request with desired body
2)BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream())); - sends empty GET request (!!)
Change it to:
// ...
conn.getOutputStream().write(dataBytes);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
and see result.

How to get response as XML from webService response?

I have to create a method for getting webService response as xml. I know how to create with Java class but problem is getting response as xml from webService.
These webServices are soap based.
Thanks in advance.
I have just solve my problem. HttpURLConnection helps me.
The following code block show how I make poster for getting xml response in java like Mozilla Poster.
public static void main(String[] args) {
try {
String uri = "http://test.com/IntegratedServices/IntegratedServices.asmx?op=GetUserInfo";
String postData = new XmlTest().xmlRequest("QWERTY10");
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // This is important. If you not set doOutput it is default value is false and throws java.net.ProtocolException: cannot write to a URLConnection exception
connection.setRequestMethod("POST"); // This is method type. If you are using GET method you can pass by url. If method post you must write
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // it is important if you post utf-8 characters
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // This three lines is importy for POST method. I wrote preceding comment.
wr.write(postData.getBytes());
wr.close();
InputStream xml = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(xml));
String line = "";
String xmlResponse = "";
while ((line = reader.readLine()) != null) {
xmlResponse += line;
}
File file = new File("D://test.xml"); // If you want to write as file to local.
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(xmlResponse);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String xmlRequest(String pin) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+ " <soap:Body>\n"
+ " <GetUserInfo xmlns=\"http://tempuri.org/\">\n"
+ " <pin>" + pin + "</pin>\n"
+ " </GetUserInfo>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
}
I hope this helps who want to get xml as response. Also I wrote detailed comment to my code.
For soap type webservice :
Parsing SOAP Response in Java
For rest look at this link:
http://duckranger.com/2011/06/jaxb-without-a-schema/

HTTP POST request with JSON Reading in Multiple Classes of Students and Varying Numbers of Assignments and Grades

I have been attempting to create an HTTP POST request that uses JSON for the purpose of sending information from a Java gradebook application to a Rails web-based application that displays those grades in the form of a report to students. This is what I have so far.
Ultimately, I want to send more than just one student's information. Furthermore, each student might have anywhere from 0 to 50 assignments, descriptions of the assignments, as well as grades for those assignments. On top of that there will be multiple classes/courses of students. All this information needs to be "read in" to the JSON object. Does anyone have any suggestions about how I could modify this code so that I could send all that data rather than the data for just one student as is shown below (as well as more than one class/course)?
public class HTTPPostRequestWithSocket {
public void sendRequest(){
try {
JSONObject obj = new JSONObject();
obj.put("instructorName", "Smith");
obj.put("courseName", "Biology 101");
obj.put("studentName1", "John Doe");
obj.put("studentNumber", new Integer(100));
obj.put("assignment1", "Test 1");
obj.put("gradeAssignment1", new Double("95.3"));
String hostname = "nameofthewebsite.com";
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: "+obj.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
obj.writeJSONString(wr);
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();
}catch (Exception e) {e.printStackTrace();}
}
}

How to Make an HTTP POST with JSON object as data?

Can anyone refer me to a single, simple resource explaining how to in Java make an HTTP POST with JSON object as data? I want to be able to do this without using Apache HTTP Client.
The following is what I've done so far. I am trying to figure out how to modify it with JSON.
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();}
}
}
JSON is just a string.
Just add the json objet as a post value.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("jsonData", new JSONObject(json)));//json
params.add(new BasicNameValuePair("param1", "somevalue"));//regular post value

Send information from PHP to Java

I want to send some information from PHP to Java. Why? Because I have a database on my server, and I get information from my database using PHP scripts.
Now I want to send that information to my client in Java. How can I do that?
I send information from Java to PHP by POST, and it works well, but I don't know how can I do the reverse.
Can you help me?
I saw this code, from a GET connection in Java... is it correct?
public String HttpClientTutorial(){
String url = "http://testes.neoscopio.com/myrepo/send.php";
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.e("[GET REQUEST]", "Network exception", e);
}
String response = content.toString();
return response;
}
P.S: I'm an android developer, not a Java developer...
From exampledepot: Sending POST request (Modified to get the output of your send.php.)
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://testes.neoscopio.com/myrepo/send.php");
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) {
}
P.S. This should work fine on Android. :)
(I usually import static java.net.URLEncoder.encode but that's a matter of taste.)

Categories

Resources