Http客户端主机名是否为null?

时间:2018-12-06 08:18:08

标签: java http-post httpclient httpresponse hostname

public class PrescriptionThread implements Runnable{ private MedicineService medServ;// = new MedicineService(); private Presciption pres ; public PrescriptionThread(Presciption pres, MedicineService medicineService) { this.pres = pres; this.medServ = medicineService; } @Override public void run() { medServ.savePrescription(pres); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } 方法与使用HttpPost来执行HttpClient的URI“ https://app_server.test.com:9100/processes”的请求正文一起使用时,我得到一个例外:主机名可能不为空

示例代码:

HttpPost

stacktrace:

HttpPost postRequest = new HttpPost("https://app_server.test.com:9100/processes.ashx"); 
StringEntity input = new StringEntity(jsonstring); 
input.setContentType("application/json"); 
postRequest.setEntity(input); 
HttpResponse response = httpClient.execute(postRequest);

1 个答案:

答案 0 :(得分:0)

您未添加创建httpClient的方式以及使用的httpClient。我尝试使用以下代码(使用org.apache.httpcomponents.httpclient,版本4.5.6)

    try
    {
        HttpClient   httpClient  = new DefaultHttpClient();
        HttpPost     postRequest = new HttpPost("https://google.com");
        StringEntity input       = new StringEntity("ttt");
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
    }
    catch (final Exception e)
    {
        System.out.print(e);
    }

它返回正确的响应“ HTTP / 1.1 405方法不允许”。

在堆栈跟踪中有很多spring-framework类是很奇怪的。您是否使用一些spring-frameworks http客户端?

我建议您:

  1. 更新您的httpclient版本(使用最新版本)

  2. 尝试使用其他网址,例如google.com等(当然,您收到http错误,例如405,但您可以看到代码正确),

  3. 尝试使用其他httpClient类或其他方式(因为httpClient 现在已弃用),