简体   繁体   English

我如何知道服务器是否将接受内容类型的特定类型?

[英]How can I know if the server will accept specific type of content-type?

I want to know what type of content the server accepts, and if I can post the data only in that format? 我想知道服务器接受哪种类型的内容,是否只能以该格式发布数据?

Update : Below is the code. 更新:下面是代码。

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class ExcelReader {

     @SuppressWarnings("unchecked")
        public static void main(String[] args) throws Exception {
            //
            // An excel file name. You can create a file name with a full 
            // path information.
            //
            String filename = "E:\\Registration Details.xlsx";

            //
            // Create an ArrayList to store the data read from excel sheet.
            //
            List sheetData = new ArrayList();

            FileInputStream fis = null;
            try {
                //
                // Create a FileInputStream that will be use to read the 
                // excel file.
                //
                fis = new FileInputStream(filename);

                //
                // Create an excel workbook from the file system.
                //
                XSSFWorkbook  workbook = new XSSFWorkbook(fis);
                //
                // Get the first sheet on the workbook.
                //
                XSSFSheet  sheet = workbook.getSheetAt(0);

                //
                // When we have a sheet object in hand we can iterator on 
                // each sheet's rows and on each row's cells. We store the 
                // data read on an ArrayList so that we can printed the 
                // content of the excel to the console.
                //
                Iterator rows = sheet.rowIterator();
                while (rows.hasNext()) {
                    XSSFRow row = (XSSFRow) rows.next();
                    Iterator cells = row.cellIterator();

                    List data = new ArrayList();
                    while (cells.hasNext()) {
                        XSSFCell cell = (XSSFCell) cells.next();
                        data.add(cell);
                    }

                    sheetData.add(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }

            showExcelData(sheetData);
        }

        private static void showExcelData(List sheetData) {
            //
            // Iterates the data and print it out to the console.
            //
            ArrayList xlsDataList = new ArrayList();
            for (int i = 0; i < sheetData.size(); i++) {
                List list = (List) sheetData.get(i);
                for (int j = 0; j < list.size(); j++) {
                    XSSFCell cell = (XSSFCell) list.get(j);
                    if(cell.getCellType()==cell.CELL_TYPE_STRING){
                        xlsDataList.add(cell.getRichStringCellValue().getString());
                   // System.out.print(
                          //  cell.getRichStringCellValue().getString());
                    }else  if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
                        xlsDataList.add(cell.getNumericCellValue());
                        //System.out.print(
                              //  cell.getNumericCellValue());
                        }
                    if (j < list.size() - 1) {
                    //    System.out.print(", ");
                    }
                }
              //  System.out.println("");
            }
            if(null!=xlsDataList && xlsDataList.size()>0){
                authenticatenewPostUrl(xlsDataList);
            }
            for(int i=0;i<xlsDataList.size();i++){
                System.out.println(xlsDataList.get(i));
            }
        }


        public static void authenticatenewPostUrl(ArrayList xlsDataList) {

            HostnameVerifier hv = new HostnameVerifier() {

                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    System.out.println("Warning: URL Host: " + urlHostName
                            + " vs. " + session.getPeerHost());
                    return true;
                }
            };
            // Now you are telling the JRE to trust any https server.
            // If you know the URL that you are connecting to then this should
            // not be a problem
            try {
                trustAllHttpsCertificates();
            } catch (Exception e) {
                System.out.println("Trustall" + e.getStackTrace());
            }
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            try {

                URL url = new URL("https://www.walmart.com/cservice/ya_index.gsp");
                 String line;

                    StringBuilder string=new StringBuilder();
                    HttpsURLConnection  ucc = (HttpsURLConnection) url.openConnection();
                    InputStream content = (InputStream) ucc.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(content));
                    while ((line = in.readLine()) != null) {
                     string.append(line);

                    }
                 Document document=Jsoup.parse(string.toString());
                    Elements elements=document.getElementsByTag("a");//("mainSpriteSliderBTN wmBTN_blue25 continue");
                    int count=0;
                    //String registrationURL="";
                    String herfURL="";
                    for(Element elem:elements)
                    {
                        Elements e=elem.getElementsByAttributeValueMatching("class", "mainSpriteSliderBTN wmBTN_blue25 continue");
                        if(e!=null && !e.toString().isEmpty())
                        {
                          System.out.println(e.get(0).toString()+"\n"+count++);
                          Element myElem=e.get(0);
                          System.out.println(myElem.attr("href"));
                          herfURL=myElem.attr("href");
                        }
                    }
                    URL registrationURL = new URL("https://www.walmart.com"+herfURL);

                //String credentials = "ptt" + ":" + "ptt123";
                String postData = "firstName="+xlsDataList.get(0)+"&lastName="+xlsDataList.get(1)+"&userName="+xlsDataList.get(2)+"&userNameConfirm="+xlsDataList.get(3)+"&pwd="+xlsDataList.get(5)+"&pwdConfirm="+xlsDataList.get(6);
               // String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
                HttpsURLConnection  uc = (HttpsURLConnection) registrationURL.openConnection();
                uc.setDoInput(true);
                uc.setDoOutput(true);
              //  uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
                uc.setRequestMethod("POST");
                uc.setRequestProperty("Accept", "*/*");
                uc.setRequestProperty("Content-Length", Integer.toString(postData.getBytes().length));
                uc.setRequestProperty("Content-Type", "text/html; charset=utf-8");

                OutputStreamWriter outputWriter = new OutputStreamWriter(uc.getOutputStream());
                outputWriter.write(postData);
                outputWriter.flush();
                outputWriter.close();
                System.out.println(uc.getResponseCode()+":::"+uc.getResponseMessage());

            } catch (MalformedURLException e) {
                e.printStackTrace();
                pw.println("Invalid URL");
            } catch (IOException e) {
                e.printStackTrace();
                pw.println("Error reading URL");
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(sw.toString());
        }

        public static class TempTrustedManager implements
        javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public boolean isServerTrusted(
            java.security.cert.X509Certificate[] certs) {
        return true;
    }

    public boolean isClientTrusted(
            java.security.cert.X509Certificate[] certs) {
        return true;
    }

    public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
        return;
    }

    public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType)
            throws java.security.cert.CertificateException {
        return;
    }
}

private static void trustAllHttpsCertificates() throws Exception {

    // Create a trust manager that does not validate certificate chains:

    javax.net.ssl.TrustManager[] trustAllCerts =

    new javax.net.ssl.TrustManager[1];

    javax.net.ssl.TrustManager tm = new TempTrustedManager();

    trustAllCerts[0] = tm;

    javax.net.ssl.SSLContext sc =

    javax.net.ssl.SSLContext.getInstance("SSL");

    sc.init(null, trustAllCerts, null);

    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(

    sc.getSocketFactory());

}

}

I thought that data is been posted to above url, but When i print the response code and response message iam getting as 500:::Internal Server Error 我以为数据已发布到上面的url,但是当我打印响应代码和响应消息时,iam会显示为500:::Internal Server Error

When i check this link internal server error 500 当我检查此链接内部服务器错误500

I came to know we have send data to server, ie accepted type only. 我知道我们已经将数据发送到服务器,即仅接受类型。

If not please correct me and how can i resolve the above issue. 如果没有,请纠正我,我该如何解决以上问题。

iam trying to post the data, i want to know what kind of data does the server accepts.Mean, we will be setting for parameter content-type. 我试图发布数据,我想知道服务器接受什么样的数据。平均值,我们将设置参数content-type。 so what kind of data can i send to particualr server 那我可以发送什么样的数据到特定服务器

You don't get the content-type from the server, you get it from the form that you POST from, or it's pre-negotiated (like in documentation). 您无法从服务器获取内容类型,也无法从POST表单获取内容类型,或者已预先协商了内容类型(例如在文档中)。 There isn't a method that you can request to get what content-type a particular resource on the server wants in a POST body. 您无法请求一种方法来获取POST正文中服务器上特定资源所需的内容类型。

If you are submitting a form from, say, an HTML page, by default it's just application/x-www-form-urlencoded , otherwise the <FORM> tag will tell you what the content-type needs to be (like multipart/form-data ). 如果要从HTML页面提交表单,则默认情况下,它只是application/x-www-form-urlencoded ,否则<FORM>标记将告诉您内容类型需要是什么(例如multipart/form-data )。

Looking at your edited post, it looks like you're POSTing data, that's application/x-www-form-urlencoded : 查看您编辑过的帖子,看起来您正在发布数据,即application/x-www-form-urlencoded

postData = "firstName="+xlsDataList.get(0)+"&lastName="+xlsDataList.get(1)+
    "&userName="+xlsDataList.get(2)+"&userNameConfirm="+xlsDataList.get(3)+
    "&pwd="+xlsDataList.get(5)+"&pwdConfirm="+xlsDataList.get(6);

But you are telling the server that it's text/html : 但是您告诉服务器它是text/html

            uc.setRequestProperty("Content-Type", "text/html; charset=utf-8");

Which is clearly wrong. 这显然是错误的。 No idea if this is what's causing your 500 error response, though. 不知道这是否是导致您的500错误响应的原因。 Conclusion: you have to know what content-type the request you are request wants its data in. There's no general way to query the server and ask. 结论:您必须知道所请求的请求将数据放入哪种内容类型。没有通用的方法来查询服务器并询问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何设置 Content-Type 以响应 application/json - How I can set Content-Type in react to application/json 如何使用 415 Unknown Media Type 记录 Spring 拒绝的 Content-Type? - How can I log the Content-Type that Spring rejects with a 415 Unknown Media Type? 强制 feign 使用特定的内容类型 - Force feign to use a specific content-type 如何在IBM HTTPD服务器上设置Content-Type HTTP标头的字符集部分? - How do I set the charset portion of the Content-Type HTTP Header on an IBM HTTPD Server? MVC-当自定义内容类型时接受JSON(不是application / json) - MVC - Accept JSON when content-type is custom (not application/json) 在Java服务器中返回内容类型 - Return content-type in java server 打开HTTP连接后如何识别内容类型? - How can I identify the content-type after opening an HTTP connection? 如何将自定义内容类型设置为 jax-rs 客户端? - How can I set a custom Content-Type to jax-rs client? Azure 功能:Java 如何接受应用程序/xml 的内容类型然后将其转换为 POJO - Azure Functions:Java How to accept content-type of application/xml then convert it to a POJO 如何在 spring-web servlet 中接受 text/csv 作为内容类型? - How to accept text/csv as content-type in spring-web servlet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM