HttpUrlConnection gerResponseCode给出连接重置异常

时间:2016-05-26 07:13:45

标签: java httpurlconnection socketexception http-response-codes connection-reset

当我尝试命中con.getResponseCode()时,我得到连接重置异常,但在网页浏览器中点击相同的网址时,它会正确返回响应,但是从我的代码中不会返回响应。请帮我看一下。

This is the code:-

private HttpURLConnection con;
private String directory;

public MIMESender(String url_path,String provider,String user,String password) throws Exception {
    super();
    // TODO Auto-generated constructor stub
    URL url = new URL(url_path);
    System.out.println("Url Path=====" + url_path);
    con = (HttpURLConnection) url.openConnection();

    con.setRequestMethod("POST");

    con.setDoOutput(true);

    con.setRequestProperty("X-XIAM-ContentProvider",provider);
    con.setRequestProperty("X-XIAM-ContentUsername",user);
    con.setRequestProperty("X-XIAM-ContentPassword",password);
    //System.setProperty("http.keepAlive", "false");
    //System.out.println("Keep Alive=========" + System.getProperty("http.keepAlive"));
}

public void setContentType(String type) throws IOException
{
    con.setRequestProperty("Content-Type",type);
}

public static MimeBodyPart createXMLPart(String xml) throws MessagingException
{
    ByteArrayDataSource fileData = new ByteArrayDataSource(xml.getBytes(),"text/xml");
    DataHandler fileDataHandler = new DataHandler(fileData);
    MimeBodyPart body = new MimeBodyPart();
    body.setDataHandler(fileDataHandler);
    body.setHeader("Content-Type",fileData.getContentType());
    return body;
}

public static MimeBodyPart createBodyPart(String filename) throws MessagingException
{
    File file = new File(filename);
    return createBodyPart(file);
}

public static MimeBodyPart createBodyPart(File file) throws MessagingException
{
    FileDataSource fileData = new FileDataSource(file);
    DataHandler fileDataHandler = new DataHandler(fileData);
    MimeBodyPart body = new MimeBodyPart();
    body.setDataHandler(fileDataHandler);
    body.setHeader("Content-Type",fileData.getContentType());
    if(!fileData.getContentType().startsWith("text"))
        body.setHeader("Content-Transfer-Encoding","base64");
    else body.setHeader("Content-Transfer-Encoding","7bit");
    body.setContentID(file.getName());
    body.setHeader("Content-Location",file.getName());
    body.setHeader("Content-Disposition","attachment; filename="+file.getName());      
    return body;
}

public static MimeBodyPart createBodyPart(String location,File file) throws MessagingException
{
    FileDataSource fileData = new FileDataSource(file);
    DataHandler fileDataHandler = new DataHandler(fileData);
    MimeBodyPart body = new MimeBodyPart();
    body.setDataHandler(fileDataHandler);
    body.setHeader("Content-Type",fileData.getContentType());
    if(!fileData.getContentType().startsWith("text"))
        body.setHeader("Content-Transfer-Encoding","base64");
    body.setContentID(file.getName());
    body.setHeader("Content-Location",location);
    body.setHeader("Content-Disposition","attachment; filename="+file.getName());   
    return body;
}

public String sendItem(String xml,String location,String filename) throws MessagingException,IOException
{

    String response = null;
    MimeMultipart mime = new MimeMultipart();
    mime.setSubType("related");                     
    String type = mime.getContentType();
    setContentType(type);

    mime.addBodyPart(MIMESender.createXMLPart(xml));

    if(!filename.equals(""))
    {   
        File file = new File(filename);
        mime.addBodyPart(MIMESender.createBodyPart(location,file));
    }
    response = submit(mime);
    return response;
}

public String send(String xml,String location,String filename) throws MessagingException,IOException
{
    String response = null;
    response = send(xml,location,new File(filename));
    return response;
}

public String send(String xml,String location,File file) throws MessagingException,IOException
{
    String response = null;
    File[] files = new File[1];
    files[0] = file;
    response = send(xml,location,files);
    return response; 
}

public String send(String xml,String location,File[] files) throws MessagingException,IOException
{
    String response = null;

    try
    {

    MimeMultipart mime = new MimeMultipart();
    mime.setSubType("related");         
    String type = mime.getContentType();
    setContentType(type);

    mime.addBodyPart(MIMESender.createXMLPart(xml));

    MimeMultipart mime_mix = new MimeMultipart();
    mime_mix.setSubType("mixed");
    for(int i=0;i<files.length;i++)
    {
        System.out.println("files : " + files[i]);
        mime_mix.addBodyPart(MIMESender.createBodyPart(files[i]));
    }

    MimeBodyPart body_mix = new MimeBodyPart();
    body_mix.setContent(mime_mix);
    body_mix.setHeader("Content-Type",mime_mix.getContentType());
    body_mix.setHeader("Content-Location",location);
    mime.addBodyPart(body_mix);

    response = submit(mime);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return response;
}

public String send(String xml,String location,File[] files,String preloc,String preview) throws MessagingException,IOException
{
    String response = null;
    MimeMultipart mime = new MimeMultipart();
    mime.setSubType("related");         
    String type = mime.getContentType();
    setContentType(type);

    mime.addBodyPart(MIMESender.createXMLPart(xml));

    if(location!=null)
    {
        System.out.println("Inside Location not equals to null");
        MimeMultipart mime_mix = new MimeMultipart();
        mime_mix.setSubType("mixed");
        for(int i=0;i<files.length;i++)
        {
            System.out.println(files[i].getAbsolutePath() + " - " + files[i].exists());
            mime_mix.addBodyPart(MIMESender.createBodyPart(files[i]));
        }

        MimeBodyPart body_mix = new MimeBodyPart();
        body_mix.setContent(mime_mix);
        body_mix.setHeader("Content-Type",mime_mix.getContentType());
        body_mix.setHeader("Content-Location",location);
        mime.addBodyPart(body_mix);
    }

    if(preloc!=null){
    File file = new File(preview);
    mime.addBodyPart(MIMESender.createBodyPart(preloc,file));
    }
    response = submit(mime);
    return response;
}

public String submit(MimeMultipart mime) throws IOException, MessagingException
{
    String response=null;
    DataOutputStream dos = new DataOutputStream(con.getOutputStream());
    dos.writeBytes("\r\n\r\n");
    mime.writeTo(dos);
    dos.flush();
    dos.close();        
    System.out.println("Connection : "+con);
    String httpCode = String.valueOf(con.getResponseCode()); // I am getting exception here..
    String respMsg = con.getResponseMessage();
    response = "HTTP/1.1 "+httpCode+" "+respMsg+"\n";

    int length = con.getContentLength();
    byte[] cnt = new byte[length];
    DataInputStream in = new DataInputStream(con.getInputStream());
    in.readFully(cnt);
    response = response + new String(cnt).replaceAll("&lt;","<").replace("&gt;",">") + "\n";

    con.disconnect();
    return response;
}

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
        String url = args[0];
        MIMESender sender = new MIMESender(url,"CP001","CP001","CP001");
        File file = new File(args[1]);
        FileInputStream in = new FileInputStream(file);
        int len = (int)file.length();
        byte[] data = new byte[len];
        in.read(data);

        int n = args.length - 3;
        File[] files = new File[n];
        for(int i=0;i<n;i++)
            files[i] = new File(args[3+i]);
        String resp = sender.sendItem(new String(data),args[2],args[2]);
        System.out.println(resp);

    } catch(IOException io){io.printStackTrace();
    } catch(MessagingException msg){msg.printStackTrace();      
    } catch(Exception e){e.printStackTrace();}
}

public String getDirectory() {
    return directory;
}

public void setDirectory(String directory) {
    this.directory = directory;
}

我的完整堆栈跟踪是: -

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.nokia.content.misc.MIMESender.submit(MIMESender.java:218)
at com.nokia.content.misc.MIMESender.send(MIMESender.java:201)
at com.nokia.content.CTUploader.sendSubItem(CTUploader.java:1202)
at com.nokia.content.CTUploader.send(CTUploader.java:800)
at com.nokia.content.CTUploader.send(CTUploader.java:502)
at com.nokia.content.ui.CPA.doSubmission(CPA.java:727)
at com.nokia.content.ui.CPA.submitMenuItemActionPerformed(CPA.java:571)
at com.nokia.content.ui.CPA.access$16(CPA.java:563)
at com.nokia.content.ui.CPA$9.actionPerformed(CPA.java:195)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

请帮我解决这个问题... 谢谢..

1 个答案:

答案 0 :(得分:0)

由于任何人都不可能仅根据代码来确定您的问题,我正在回答有关如何继续进行的建议。

鉴于它可以在浏览器中运行,但不能从您的代码中运行,问题可能在于您的代码不会发送与浏览器完全相同的事务。最可能的区别是缺少或额外的HTTP标头,或User-Agent标头的差异导致服务器关闭连接。

调试此问题的最简单方法是使用Wireshark捕获网络流量并确定浏览器和代码之间的不同之处。如果您发现存在重大差异并仍需要帮助,请发布另一个显示相关差异的问题。