Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在键/值对中发布数据?_Java_Json_Http Post - Fatal编程技术网

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

Java 如何在键/值对中发布数据?,java,json,http-post,Java,Json,Http Post,我需要将数据发布到特定的url 在内容中,我需要在内容数组和json格式的元标题中发布html URL oracle = new URL(""); try (BufferedReader in = new BufferedReader( new InputStreamReader(oracle.openStream()))) { String inputLine1;

我需要将数据发布到特定的url 在内容中,我需要在内容数组和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);}  */
            }
    } 
    }   
URL oracle=newurl(“”);
try(BufferedReader in=新的BufferedReader(
新的InputStreamReader(oracle.openStream())){
字符串输入1;
而((inputLine1=in.readLine())!=null){
System.out.println(inputLine1);
com.eclipsesource.json.JsonObject=json.parse(inputLine1.asObject();
com.eclipsesource.json.JsonArray items=json.parse(inputLine1.asObject().get(“data”).asArray();
用于(JsonValue项:项){
//System.out.println(item.toString());
字符串名称=item.asObject().getString(“id”,“未知项”);
System.out.println(名称);
字符串数量=item.asObject().getString(“url”、“id”);
//JSONArray jsonArray2=新JSONArray(数量);
系统输出打印项次(数量);
/*Platform.runLater(()->{
试一试{
睡眠(10000);
}捕获(中断异常例外){
Logger.getLogger(HV1.class.getName()).log(Level.SEVERE,null,ex);
}*/
Img.荷载(数量);
网址;
InputStream=null;
缓冲剂;
弦线;
url=新url(数量);
is=url.openStream();//引发IOException
br=新的BufferedReader(新的InputStreamReader(is));
而((line=br.readLine())!=null){
系统输出打印项次(行);
byte[]postData=line.getBytes(StandardCharsets.UTF_8);
wb2.荷载(线);
字符串originalUrl=“”;
字符串newUrl=originalUrl.replace(“ID”,名称);
System.out.println(newUrl);
URL url1=新URL(新URL);
Map params=新建LinkedHashMap();
参数put(“内容”,postData);
参数put(“meta”、“abc”);
StringBuilder postData1=新的StringBuilder();
对于(Map.Entry参数:params.entrySet()){
如果(postData1.length()!=0)postData1.append('&');
append(URLEncoder.encode(param.getKey(),“UTF-8”);
postData1.append('=');
append(URLEncoder.encode(String.valueOf(param.getValue()),“UTF-8”);
}
字节[]postDataBytes=postData1.toString().getBytes(“UTF-8”);
HttpURLConnection conn=(HttpURLConnection)url1.openConnection();
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“内容类型”、“应用程序/x-www-form-urlencoded”);
conn.setRequestProperty(“内容长度”,String.valueOf(postDataBytes.Length));
连接设置输出(真);
conn.getOutputStream().write(postDataBytes);
Reader in1=新的BufferedReader(新的InputStreamReader(conn.getInputStream(),“UTF-8”);
for(int c;(c=in1.read())>=0;)
系统输出打印((字符)c);
/*试试{
睡眠(400);
}catch(InterruptedException e){System.out.println(e);}*/
}
} 
}   

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

请看一下之前关于利用BasicNameValuePairs的HTTP Post参数的答案

下面是来自该答案的一段相关代码

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);
HttpClient-HttpClient;
HttpPost-HttpPost;
ArrayList后参数;
httpclient=新的DefaultHttpClient();
httppost=newhttppost(“您的登录链接”);
postParameters=新的ArrayList();
添加(新的BasicNameValuePair(“param1”,“param1_值”);
添加(新的BasicNameValuePair(“param2”、“param2_值”);
setEntity(新的UrlEncodedFormEntity(后参数,“UTF-8”);
HttpResponse response=httpclient.execute(httpPost);

如果您不熟悉要实现的目标,最好使用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;
    }
最后你需要做一些事情,比如:

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

}
/*package*/T sendRequest(类responseClass、对象requestEpo、字符串uri){
试一试{
//将封装的内容类型解析为媒体类型
HttpHeaders=新的HttpHeaders();
MediaType requestContentType requestContentType=MediaType.APPLICATION_JSON;
//将内容类型和接受标头设置为此类型
headers.setContentType(requestContentType);
setAccept(Collections.singletonList(requestContentType));
//将数据对象解析为JSON
字符串requestJSONAsString=“”;
if(request.getData()!=null){
试一试{
requestJSONAsString=RestObjectMapper.getInstance().writeValueAsString(requestEpo);
}捕获(JsonProcessingException ex){
抛出新的InternalServerErrorException(String.format(“错误分析:%s”,requestEpo.getClass().getSimpleName()),例如);
}
}
//执行发送请求
返回sendRequest(responseClass、uri、headers、httpMethod、requestJSONAsString);
}最后{
LOG.debug(“结束发送请求”);
}
}
private T sendRequest(最终类responseClass、最终字符串uri、最终HttpHeaders、最终HttpMethod、最终HttpMethod、字符串请求JSON){
试一试{
LOG.debug(String.format(“使用:%s%s%s%s启动sendRequest”,uri,httpHeaders,httpMethod,requestJSON));
RestTemplate rest=新建RestTemplate();
ClientHttpRequestFactory restFactory=rest.getRequestFactory();
如果(事实上)
/*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");
    }

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