2017-12-19 26 views
-1

나는 특정 URL에 의 내용을 게시해야하는데, 그 내용은 콘텐츠 배열에 html과 json 형식의 메타 헤더를 ​​게시해야합니다.키/값 쌍에 데이터를 게시하는 방법은 무엇입니까?

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

이 내가 당신의 소중한 시간을 내 문제의 감사를 해결하는 방법이 내 updted 코드 (답)입니다.

+0

데이터가 텍스트와 json 형식으로 게시되었지만 키/값 쌍이 필요하다는 언급이있는이 게시물에는 중복이 없습니다. –

+0

질문에 대한 대답은 키/값 쌍을 게시하는 방법을 보여줍니다. –

답변

-2

BasicNameValuePairs를 악용하는 HTTP 게시 매개 변수에 대한 이전 답변을 살펴보십시오. 여기

Name Value Pairs

그 답 코드에서의 해당 부분이다.

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); 
+0

이 링크는 질문에 대답 할 수 있지만 답변의 핵심 부분을 여기에 포함시키고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [검토 중] (리뷰/저품절 게시물/18297365) –

+0

감사합니다. @WaqasBukhary - 코드 스 니펫 – PillHead

+0

으로 업데이트했습니다. 내 답변을 업데이트했지만 내용과 메타에서 아직 내용을 얻지 못했습니다. –

-1

당신은 당신이 달성하려고하는 무엇에 익숙하지 않은 경우, 요청을 통해 보내는 JSON을 생성하는 봄과 잭슨 같은 것을 사용하는 것입니다 최저 : 이것은 단지 기본 구현

입니다

및 EPO

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

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

전송 및 KeyV aswell 할 aluePairEPO :

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 

... 

그리고 마침내

당신이 할 필요가 뭔가 같은 : RestObjectMapper가

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

} 

: ResponseClass 다른 EPO 결과입니다 그런데

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

(JSON) 에 매핑됩니다.