如何在键/值对中发布数据?

时间:2017-12-19 09:23:56

标签: java json http-post

我需要将数据发布到特定网址 在内容中我需要在内容数组和json格式的元标题中发布html。

    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");   

这是我尝试但我在文本/平原发布但我想发布键/值对。

更新代码

 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);}  */
            }
    } 
    }   

这是我的更新代码(回答)这是我解决问题的方法,感谢您宝贵的时间。

2 个答案:

答案 0 :(得分:-1)

如果你不熟悉你想要实现的目标,那么Best会使用像Spring和Jackson这样的东西通过请求创建一个JSON发送:

这只是基本实现

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

EPO转移数据

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;
    }

以及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

...

最后你需要做一些事情:

/*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");
    }

}

其中RestObjectMapper是:

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;
}

顺便说一句,ResponseClass是另一个EPO,结果(JSON)将被映射到。

答案 1 :(得分:-2)

查看以前关于利用BasicNameValuePairs的HTTP Post参数的回答。

Name Value Pairs

以下是该答案的相关代码。

{{1}}