-1

i need to post data to particular url in which in content i need to post html in content array and in meta headers in json format.

    URL oracle = new URL("");
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(oracle.openStream()))) {
                String inputLine1;
                while ((inputLine1 = in.readLine()) != null) {
                    System.out.println(inputLine1);
                    com.eclipsesource.json.JsonObject object = Json.parse(inputLine1).asObject();
                    com.eclipsesource.json.JsonArray items = Json.parse(inputLine1).asObject().get("data").asArray();

                    for (JsonValue item : items) {
                        //System.out.println(item.toString());
                        String name = item.asObject().getString("id", "Unknown Item");
                        System.out.println(name);

                        String quantity = item.asObject().getString("url", "id");
                       // JSONArray jsonArray2 = new JSONArray(quantity);
                         System.out.println(quantity);

                       /* Platform.runLater(() ->{
                            try {
                                Thread.sleep(10000);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(HV1.class.getName()).log(Level.SEVERE, null, ex);
                            }*/
                        Img.load(quantity);
                                URL url;
        InputStream is = null;
        BufferedReader br;
        String line;
                 url = new URL(quantity);
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(new InputStreamReader(is));

            while ((line = br.readLine()) != null) {
                System.out.println(line);
                byte[] postData= line.getBytes( StandardCharsets.UTF_8 );
                wb2.load(line);
                String originalUrl = "";
    String newUrl = originalUrl.replace("ID", name);
    System.out.println(newUrl);

    String request        = newUrl;
    URL    url1            = new URL( request );
    HttpURLConnection conn= (HttpURLConnection) url1.openConnection();           
    conn.setDoOutput( true );
    conn.setInstanceFollowRedirects( false );
    conn.setRequestMethod( "POST" );
    conn.setRequestProperty( "Content-Type", "text/plain"); 
    conn.setRequestProperty( "charset", "utf-8");
    //conn.setRequestProperty( "Content-Length", Integer.toString( line ));
    conn.setUseCaches( false );
    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
     wr.write(postData);
      System.out.println("200 ok");   

this is what i tried but i had post in text/plain but i want to post in key/value pair.

updated code

 URL oracle = new URL("");
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(oracle.openStream()))) {
            String inputLine1;
            while ((inputLine1 = in.readLine()) != null) {
                System.out.println(inputLine1);
                com.eclipsesource.json.JsonObject object = Json.parse(inputLine1).asObject();
                com.eclipsesource.json.JsonArray items = Json.parse(inputLine1).asObject().get("data").asArray();

                for (JsonValue item : items) {
                    //System.out.println(item.toString());
                    String name = item.asObject().getString("id", "Unknown Item");
                    System.out.println(name);

                    String quantity = item.asObject().getString("url", "id");
                   // JSONArray jsonArray2 = new JSONArray(quantity);
                     System.out.println(quantity);

                   /* Platform.runLater(() ->{
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(HV1.class.getName()).log(Level.SEVERE, null, ex);
                        }*/
                    Img.load(quantity);
                            URL url;
    InputStream is = null;
    BufferedReader br;
    String line;
             url = new URL(quantity);
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
            byte[] postData= line.getBytes( StandardCharsets.UTF_8 );

            wb2.load(line);
            String originalUrl = "";
String newUrl = originalUrl.replace("ID", name);
System.out.println(newUrl);

 URL url1 = new URL(newUrl);
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("content", postData);
        params.put("meta", "abc");


        StringBuilder postData1 = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData1.length() != 0) postData1.append('&');
            postData1.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData1.append('=');
            postData1.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData1.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in1 = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in1.read()) >= 0;)
            System.out.print((char)c);

        /*          try{  
       Thread.sleep(400);  
      }catch(InterruptedException e){System.out.println(e);}  */
            }
    } 
    }   

this is my updted code(answer) this is how i solve my problem thanks for your precious time.

2
  • its not a duplicate in this post which u had mention the data is posted in text and json form but i want in key/value pair Commented Dec 19, 2017 at 9:40
  • The answers to the question do show how to post key/value pairs. Commented Dec 19, 2017 at 10:22

2 Answers 2

2

Take a look at this previous answer regarding HTTP Post parameters that exploit BasicNameValuePairs.

Name Value Pairs

Here is a pertinent piece of code from that answer.

HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("your login link");


postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));

httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));

HttpResponse response = httpclient.execute(httpPost);
Sign up to request clarification or add additional context in comments.

4 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
Thanks @WaqasBukhary - I've updated accordingly with a code snippet
i had updated my answer but still im not getting anything in content and meta
have you tried the code that I have suggested? Your updated answer appears to use a different solution
-1

Best would be using something like Spring and Jackson to create a JSON sending via a request, if you are not familiar with what you are trying to achieve:

This is just basic implementation

private final String uri = "yoururl.de/asdfasd";
private final HttpMethod httpMethod = HttpMethod.POST;
private final ContentType contentType = ContentType.json;

And EPO to transfer the Data

SendKeyValuePairsEPO implements Serializable{

    private static final long serialVersionUID = 5311348008314829094L;
    private final Integer startIndex;
    private final Integer size;
    private final Integer totalSize;

    private final List<KeyValuePairEPO> values;

    /**
     * Contructor
     *
     * @param startIndex start searching index
     * @param size       requested result size
     * @param totalSize  total size of available records
     * @param values      the key value pairs
     */
    public SendKeyValuePairsEPO(@JsonProperty("startIndex") final Integer startIndex,
                                  @JsonProperty("size") final Integer size,
                                  @JsonProperty("totalSize") final Integer totalSize,
                                  @JsonProperty("values") final List<KeyValuePairEPO> values) {
        this.startIndex = startIndex;
        this.size = size;
        this.totalSize = totalSize;
        this.values = values;
    }

and aswell a KeyValuePairEPO:

KeyValuePairEPO implements Serializable{

    private static final long serialVersionUID = 5311348008314829094L;
    private final String key;
    private final String value;
    private final String type; //maybe you need a type to tell what kind of value it is

...

And at last you will need to do something like:

/*package*/ <T> T sendRequest(Class<T> responseClass, Object requestEpo, String uri) {
    try {
        //Parse encapsulated COntent type to media type
        HttpHeaders headers = new HttpHeaders();
        MediaType requestContentType requestContentType = MediaType.APPLICATION_JSON;

        //Set content type and accept header to this type
        headers.setContentType(requestContentType);
        headers.setAccept(Collections.singletonList(requestContentType));
        //Parse the data object to a JSON
        String requestJSONAsString = "";
        if (request.getData() != null) {
            try {
                requestJSONAsString = RestObjectMapper.getInstance().writeValueAsString(requestEpo);
            } catch (JsonProcessingException ex) {
                throw new InternalServerErrorException(String.format("Error parsing: %s", requestEpo.getClass().getSimpleName()), ex);
            }
        }
        //Perform the send request
        return sendRequest(responseClass, uri, headers, httpMethod, requestJSONAsString);

    } finally {
        LOG.debug("Ended sendRequest");
    }
}

private <T> T sendRequest(final Class<T> responseClass, final String uri, final HttpHeaders httpHeaders, final HttpMethod httpMethod, String requestJSON) {
    try {
        LOG.debug(String.format("Start sendRequest with:%s %s %s %s", uri, httpHeaders, httpMethod, requestJSON));
        RestTemplate rest = new RestTemplate();
        ClientHttpRequestFactory restFactory = rest.getRequestFactory();
        if(restFactory instanceof SimpleClientHttpRequestFactory){
            ((SimpleClientHttpRequestFactory)restFactory).setReadTimeout(REQUEST_TIMEOUT);
            ((SimpleClientHttpRequestFactory)restFactory).setConnectTimeout(REQUEST_TIMEOUT);
        }

        HttpEntity<String> entity = new HttpEntity<>(requestJSON, httpHeaders);

        final ResponseEntity<String> response = rest.exchange(uri, httpMethod, entity, String.class);
        LOG.debug("Status:" + response.getStatusCode().toString());
        String returnedPayload = response.getBody();
        return RestObjectMapper.getInstance().readValue(returnedPayload, responseClass);
    } catch (HttpStatusCodeException ex) {
        LOG.error("HTTP Error in sendRequest: " + ex.getMessage());
        switch (ex.getStatusCode()) {
            case BAD_REQUEST:
                throw new BadRequestException(uri, ex);
            case NOT_FOUND:
                throw new NotFoundException(uri, ex);
            case FORBIDDEN:
                throw new ForbiddenException(uri, ex);
            case REQUEST_TIMEOUT:
                throw new RequestTimeoutException(ex, REQUEST_TIMEOUT);
            default:
                throw new InternalServerErrorException(ex);
        }
    } catch (Exception ex) {
        LOG.error("Error in sendRequest: " + ex.getMessage());
        throw new InternalServerErrorException(ex);
    } finally {
        LOG.debug("Ended sendRequest");
    }

}

where RestObjectMapper is:

public class RestObjectMapper extends ObjectMapper {
public static final String EMPTY_JSON = "{}";
private static final long serialVersionUID = 3924442982193452932L;

/**
 * Singleton Instance
 * Pattern: Initialization-on-demand holder idiom:
 * <ul>
 * <li>the class loader loads classes when they are first accessed (in this case Holder's only access is within the getInstance() method)</li>
 * <li>when a class is loaded, and before anyone can use it, all static initializers are guaranteed to be executed (that's when Holder's static block fires)</li>
 * <li>the class loader has its own synchronization built right in that make the above two points guaranteed to be threadsafe</li></ul>
 */
private static class INSTANCE_HOLDER {
    private static final RestObjectMapper INSTANCE = new RestObjectMapper();
}

private RestObjectMapper() {
    super();
    configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
    configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}

/**
 * Gets the singleton Instance of the JSON Mapper
 *
 * @return the singleton instance
 */
public static RestObjectMapper getInstance() {
    return INSTANCE_HOLDER.INSTANCE;
}

By the way ResponseClass is another EPO the result (JSON) will be mapped to.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.