http post not working from code but working from p

2019-06-27 08:20发布

问题:

Here is code

public class PostRequestMain {

    private static String ReadFile(String path) {
        String entityBody = new String();
        FileReader file;
        try {
            file = new FileReader(path);
            try {
                entityBody = IOUtils.toString(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        return entityBody;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "text/plain");
        map.put("userName", "username");
        map.put("password", "pass");

        String payLoad = ReadFile("src/main/resources/SamplePayload.html");

        headers.setAll(map);
        HttpEntity<String> requestPayload = new HttpEntity<String>(payLoad,headers);
        String url = "http://domain/path";

        ResponseEntity<String> responseEntity = null;

        UriComponentsBuilder uriComponents = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("param1", "value1");

        try {
            responseEntity = new RestTemplate().postForEntity(uriComponents.build().encode().toUri(), requestPayload, String.class);
        } catch (HttpStatusCodeException ex) {
            System.out.println("Status code = " + ex.getStatusCode());
        }

        String entityResponse = responseEntity.getBody();
        System.out.println(entityResponse);
    }

}

when I run above code it gives me exception

Exception in thread "main"

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://domain/path ":Connection reset; nested exception is java.net.SocketException: Connection reset
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:503)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:465)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:342)
    at sprinthttp1.PostRequestMain.main(PostRequestMain.java:61)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:209)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
    at org.springframework.http.client.SimpleClientHttpResponse.getRawStatusCode(SimpleClientHttpResponse.java:47)
    at org.springframework.http.client.AbstractClientHttpResponse.getStatusCode(AbstractClientHttpResponse.java:32)
    at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:55)
    at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:49)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:489)
    ... 3 more

But when I try make post request to same URL with Postman I get proper results. I tried different ways to post request but every time same error. Any ideas what could be issue?

回答1:

Without viewing concrete example of domain which refuses your connection - it is hard to say exactly what's going wrong.

But, from my experience, I had very similar problems, and it is quite often when servers block requests which contain "java" keyword inside User-Agent header, which comes from your code by default (not exactly "java", but string which contains it). This is done specifically in order to block various bots.

So I would suggest you add User-Agent header and set it something like Mozilla/5.0 or simply Postman emulator and see how it will work.



回答2:

Just taking shot based on my experience, probably you are behind a proxy(especially if you are trying this in your office). Postman would work as the proxy is already configured in browser. Try to set proxy info in the program as below, // HTTP/HTTPS Proxy

    System.setProperty("http.proxyHost", proxyhost);
    System.setProperty("http.proxyPort", proxyport;
    System.setProperty("https.proxyHost", proxyhost);
    System.setProperty("https.proxyPort", proxyport);


回答3:

I faced the same problem.It is because I was using the office internet which might be using some proxies.So I tried using my mobile Internet through Hotspot and I was able to fetch the results.

This might happen due to some proxy preventing it from fetching the results.

Thanks