Wie poste ich Formulardaten im JSON-Format?Java

Java-Forum
Anonymous
 Wie poste ich Formulardaten im JSON-Format?

Post by Anonymous »

Das Posten von Argumentdaten aus meinem Formular funktioniert einwandfrei, aber ich muss dieselben Informationen mit JSON posten. Wie kann das gemacht werden.
Mein Formular sieht so aus.

Code: Select all






Und mein JSON-String sieht so aus.

Code: Select all

{
"name":"Josh U",
"email":"[email protected]",
"about":"Get rich programming or die tryna be something else",
"file":"@/home/josh/image.png"
}
Ich habe versucht, diese JSON-Zeichenfolge zu verwenden, erhalte jedoch Folgendes

Code: Select all

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 500
at com.ijoshluisaac.restful.client.RESTFulClientPostUsingJavaHTTPClientLibrary.main(RESTFulClientPostUsingJavaHTTPClientLibrary.java:35)
Mein JAVA-Code sieht so aus

Code: Select all

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RESTFulClientPostUsingJavaHTTPClientLibrary {

// JSON content to post
private static final String JSON_OBJECT = "{\"name\":\"Josh U\",\"email\":\"[email protected]\",\"about\":\"Get rich programming or die tryna be something else\",\"file\":\"/home/josh/image.png\"}";

//Web services URLs
private static final String URL_SR = "http://myrestfulservice.com/";

public static void main(String[] args) {

try {
URL url = new URL(URL_SR);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

OutputStream os = conn.getOutputStream();
os.write(JSON_OBJECT.getBytes());
os.flush();

if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));

String output;
System.out.println("Successfully Executed RESTFul POST .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}

conn.disconnect();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post