Java HTTPUrlConnection返回500状态代码

use*_*624 7 java httpurlconnection

我正在尝试使用HTTPUrlConnection获取URL,但是我总是得到500个代码,但是当我尝试从浏览器访问相同的URL或使用curl时,它工作正常!

这是代码

try{
    URL url = new URL("theurl"); 
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpcon.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:14.0) Gecko/20100101 Firefox/14.0.1");
    System.out.println(httpcon.getHeaderFields());
    }catch (Exception e) {
        System.out.println("exception "+e);
    }
Run Code Online (Sandbox Code Playgroud)

当我打印标题字段时,它会显示500个代码..当我将URL更改为google.com之类的其他内容时,它可以正常工作.但我不明白为什么它在这里不起作用,但它在浏览器和curl上工作正常.

任何帮助将受到高度赞赏..

谢谢,

Des*_*boy 8

这主要是因为编码而发生的.如果您使用浏览器确定,但在程序中获得500(内部服务器错误),那是因为浏览器具有关于字符集和内容类型的高度复杂的代码.

这是我的代码,它适用于ISO8859_1作为charset和英语的情况.

public void sendPost(String Url, String params) throws Exception {


    String url=Url;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestProperty("Acceptcharset", "en-us");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("charset", "EN-US");
    con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    String urlParameters=params;
    // Send post request
    con.setDoOutput(true);
    con.setDoInput(true);
    con.connect();
    //con.

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());
    this.response=response.toString();
    con.disconnect();

}
Run Code Online (Sandbox Code Playgroud)

在主程序中,将其称为:

myclassname.sendPost("https://change.this2webaddress.desphilboy.com/websitealias/orwebpath/someaction","paramname="+URLEncoder.encode(urlparam,"ISO8859_1"))
Run Code Online (Sandbox Code Playgroud)


San*_*hak 6

状态代码500表明Web服务器上的代码已经崩溃.使用HttpURLConnection#getErrorStream()来更好地了解错误.请参阅Http状态代码500