简体   繁体   中英

Posting JSON data from txt file to URL

I need to post JSON data from a text file to a url.I have not come across such a scenario.

I came across posting JSON data using HttpUrlConnection.

My JSON DATA :
{
"request": {
"header": {
"signature": "BHNUMS",
"details": {
"productCategoryCode": "01",
"specVersion": "04"
}
},
"transaction": {
"primaryAccountNumber": "8961060000402122658",
"processingCode": "725400",
"transactionAmount": "000000000200",
"transmissionDateTime": "150505141718",
"systemTraceAuditNumber": "035689",
"localTransactionTime": "141718",
"localTransactionDate": "150505",
"merchantCategoryCode": "0443",
"pointOfServiceEntryMode": "021",
"pointOfServiceConditionCode":"00",
"transactionFeeAmount":"000000000200",
"acquiringInstitutionIdentifier": "10998156762",
"track2Data":";8961060000402122658=4912?",
"retrievalReferenceNumber": "44436440441",
"merchantTerminalId": "87654     987   ",
"merchantIdentifier": "10998156762",
"merchantLocation": "688 PACIFIC HIGHWAYYY CHHHHATSWOOD NSWAU",
"transactionCurrencyCode": "840",
"additionalTxnFields": 
{ "productId": "07675018955" ,
   "externalAccountNumber":"353142040651369",
   }
}
}
} 

URL :

http://10.18.141.12:30305/transaction/v/transactionw

My Code :

public static void main(String[] args) throws IOException {
    try {

        URL url = new URL("http://10.38.141.32:30304/transaction/v2/transaction");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "";

        OutputStream os = conn.getOutputStream();
        os.write(input.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("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

    }

}

String input= "" ; // I need to pass the JSON data here but not sure how to pass it.

reading from file and setting it as a string I will be able to do. But for trial purpose I had to assign String input to the JSON data mentioned above, but due to qoutes and braces I was not able to format it as a string.

Online resources explains the data to be formated in this format ( String input="{\\"qty\\":100,\\"name\\":\\"iPad 4\\"}"; )

but I have no idea how to format such big json data manually.

I am not sure if this is right, but I am not able to see the expected output. As I am completely new to this concept I am not able to tweak the code.

If anyone could help me out it would be of great help.

If you have valid JSON text in the file, you do not have to parse it yourself. However, if you need to check if the JSON is valid try writing a parser a choose a parser from the world wide web. The first step is to open the file and read its contents, like so:

final StringBuilder sb = new StringBuilder();
final BufferedReader br = new BufferedReader(new FileReader("your_file_name.txt"));

String line;
while ((line = br.readLine()) != null)
    sb.append(line); // Add to string builder

final String input = br.toString(); // Write this string to the connection body
// To minimalize characters transfer it to a JSON and then some JSONWriter which doesn't format so you don't have any spacelike characters in the string

The rest you have figured out by yourself ;)

To hard-code the JSON as String you need to escape every single double-quote with a backslash. For example, if your JSON looks like this:

{
  "foo": "1",
  "bar": "2"
}

your String declaration has to look like this:

String put = "{ \"foo\": \"1\", \"bar\": \"2\" }";

Note: IDEs like IntelliJ IDEA will escape the string for you, if you paste it into the code.

To read the file into a String , use commons-io :

String input = FileUtils.readFileToString(new File("/path/to/your/file.json"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM