小编Bli*_*1eg的帖子

HttpURLConnection POST,conn.getOutputStream()抛出异常

我想通过使用HttpURLConnection进行POST.我在两个方面尝试这个,但在做的时候我总是得到一个例外:conn.getOutputStream();

我在两种情况下得到的例外是:

java.net.SocketException:操作超时:connect:可能是由于地址无效

功能1:

public void makePost(String title, String comment, File file) {
    try {
        URL servlet = new URL("http://" + "www.server.com/daten/web/test/testupload.nsf/upload?CreateDocument");            
        HttpURLConnection conn=(HttpURLConnection)servlet.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        String boundary = "---------------------------7d226f700d0";
        conn.setRequestProperty("Content-type","multipart/form-data; boundary=" + boundary);
        //conn.setRequestProperty("Referer", "http://127.0.0.1/index.jsp");
        conn.setRequestProperty("Cache-Control", "no-cache");

        OutputStream os = conn.getOutputStream(); //exception throws here!
        DataOutputStream out = new DataOutputStream(os);
        out.writeBytes("--" + boundary + "\r\n");
        writeParam(INPUT_TITLE, title, out, boundary);
        writeParam(INPUT_COMMENT, comment, out, boundary);
        writeFile(INPUT_FILE, file.getName(), out, boundary);
        out.flush();
        out.close();

        InputStream stream = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(stream); …
Run Code Online (Sandbox Code Playgroud)

java post http httpurlconnection

3
推荐指数
1
解决办法
4万
查看次数

覆盖python日志配置

我想使用一个外部模块,但这个模块配置了记录器,我不知道如何覆盖它以记录到文件

#my main.py
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logging.basicConfig(filename='/home/pi/thermostat/server.log',level=logging.DEBUG)
logging.basicConfig(format='%(asctime)s %(message)s')
logger = logging.getLogger(__name__)    

termo = SHT1x(dataPin, clkPin, SHT1x.GPIO_BOARD) #this one configures the log also

def main():
    logger.info("SERVER START")
    return

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

我正在使用的模块正在做:

#SHT1x module
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(____name____)

def main():
    #....

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

所以我的程序记录到控制台而不是 server.log 有没有办法覆盖这种行为?

python logging module

3
推荐指数
1
解决办法
2187
查看次数

C#Serialization over socket,一个类正在序列化另一个没有

我正在尝试在C#中为学校项目制作一个客户端 - 服务器应用程序我的问题是一个类被序列化好并通过套接字发送,而另一个不是,我无法弄明白.

Employee类(以及Bonus)正在被序列化,但是当我尝试将一个Transfer实例传递给formater时

formatter.Serialize(stream, transferObj);
Run Code Online (Sandbox Code Playgroud)

它抛出异常:带有消息的NotSupportedException:内存流不可扩展.

sendToServer()

 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("127.0.0.1");
        System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 6666);
        socket.Connect("127.0.0.1", 6666);


        Transfer t = new Transfer();

        Employee e = new Employee(); 
        Bonus b = new Bonus(); b.setAmmount(234); b.setDescription("xxxx");
        e.getBonuses().Add(b);

        byte[] buffer = new byte[1000];
        System.Console.WriteLine("client started");

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream(buffer);


            formatter.Serialize(stream, e);
             // Employee and Bonus are serialized but not Transfer
            stream.Flush();

            socket.Send(buffer,buffer.Length,0);
Run Code Online (Sandbox Code Playgroud)

员工类

using System;
using System.Collections.Generic; …
Run Code Online (Sandbox Code Playgroud)

c# sockets serialization stream formatter

2
推荐指数
1
解决办法
4404
查看次数

Java Xpath表达式

我有以下XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/" 
     jersey:generatedBy="Jersey: 1.0.2 02/11/2009 07:45 PM"/>
<resources base="http://localhost:8080/stock/">
    <resource path="categories"> (<<---I want to get here)
        <method id="getCategoriesResource" name="GET">
Run Code Online (Sandbox Code Playgroud)

我想得到的价值,resource/@path所以我有以下Java代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
// get the xml to parse from URI
Document doc = builder.parse(serviceUri + "application.wadl"); 
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression expression = 
        xpath.compile("/application/resources/resource/@path");
this.baseUri = (String) expression.evaluate(doc, XPathConstants.STRING);
Run Code Online (Sandbox Code Playgroud)

使用此XPath表达式,result(baseUri)始终为空字符串("").

java xml xpath

2
推荐指数
1
解决办法
2149
查看次数

带注释的Spring MVC 3验证 - 不显示形式:错误

我已经坚持了大约一个小时,这不是我第一次这样做,但我无法弄明白.

它应该显示表单错误,而不是它抛出此异常.

LE:我在此期间设法解决了异常,但我仍然无法看到错误.他们没有呈现

org.springframework.web.util.NestedServletException:请求处理失败; 嵌套异常是org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1 errors字段'name'上对象'category'中的字段错误:被拒绝的值[jk]; 代码[Range.category.name,Range.name,Range.java.lang.String,Range]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [category.name,name]; 参数[]; 默认消息[name],25,3]; 默认消息[gfhghj] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)javax.servlet.http.HttpServlet.service (HttpServlet.java:637)javax.servlet.http.HttpServlet.service(httpServlet.java:717)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:311)org.springframework.security.web .access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy.java:323)org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springfr amework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springframework.security.web.authentication.AnonymousAuthenticationFilter. doFilter(AnonymousAuthenticationFilter.java:113)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)org. springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain. doFilter(FilterChainProxy.java:323)org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticat ionFilter.java:150)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)org.springframework. security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain. doFilter(FilterChainProxy.java:323)org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323)org. springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java: 76)org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

@Controller
@RequestMapping("/category")
public class CategoryController {

@Autowired
StockGateway stockGateway;

@RequestMapping(value = "add", method = RequestMethod.POST)
public String addCategory(@Valid @ModelAttribute("category") CategoryAdd category, ModelMap model,
        BindingResult binding) {

    if (binding.hasErrors()) {
        return "category.add";
    } …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc

2
推荐指数
1
解决办法
2万
查看次数

C命名管道(fifo).父进程陷入困境

我想创建一个简单的程序,该fork,并且子进入命名管道,父进程从命名管道读取和显示.问题是它进入了父进程,进行了第一次printf然后它变得奇怪,它没有做任何其他事情,没有进入第二个printf,它只是在控制台中输入的方式.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
char t[100];
mkfifo("myfifo",777);
pid_t pid;
pid = fork();
if (pid==0)
{
    //execl("fifo2","fifo2",(char*)0);
    char r[100];
    printf("scrie2->");
    scanf("%s",r);

    int fp;
    fp = open("myfifo",O_WRONLY);
    write(fp,r,99);
    close(fp);
    printf("exit kid \n");
    exit(0);
} else
{
    wait(0);
    printf("entered parent \n"); // <- this it prints
    // whats below this line apparently its not being executed
    int fz; printf("1"); 
    fz = open("myfifo",O_RDONLY); printf("2");
    printf("fd: %d",fz);
    char p[100];
    int size; …
Run Code Online (Sandbox Code Playgroud)

c fork pipe fifo

1
推荐指数
1
解决办法
1万
查看次数

获取计划任务的结果

我正在尝试学习java并发API,对于我的练习,我想安排一个作业每隔X秒定期运行一次.该作业将计算随机数.

我想在完成后立即获得计划任务的结果.我无法仅使用API​​完成此操作,因此我将其破解.

有没有办法更好地做到这一点,而不使用低级机制?我希望能够删除同步MyRandomGiverTask.getResult(),而是使用类似的东西ScheduledFuture.get().但在我的代码中,ScheduledFuture永远不会完成/完成.这是我目前的解决方案:

class A {
    public static void main() {
        MyRandomGiverTask task = new MyRandomGiverTask(200);
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ScheduledFuture<Double> scheduledDouble =
            (ScheduledFuture<Double>) scheduler
                .scheduleAtFixedRate(task, 1, 4, TimeUnit.SECONDS);
        while (true) {
            System.out.println(" >> " + task.getResult());
        }
    }
    public class MyRandomGiverTask implements Runnable {
        MyRandomGiver giver = new MyRandomGiver();
        int param;
        double result;
        public MyRandomGiverTask(int param) { this.param = param; }
        @Override public void run() { result = giver.getRandom(param); }
        public double getResult() {
            try …
Run Code Online (Sandbox Code Playgroud)

java concurrency scheduling scheduled-tasks java.util.concurrent

1
推荐指数
1
解决办法
2206
查看次数