所以我试图发布到一个URL(我无法显示,因为它是敏感信息),但我一直收到401错误,这意味着未经授权。我有证书,但我不知道如何设置它们。我有一个用户名,密码和一个角色。
public class GSONPost {
public static void main(String[] args) {
Person personObj = new Person();
personObj.setOrganization("ACC");
personObj.setFirstName("Harry");
personObj.setLastName("Smith");
personObj.setPhone1(null);
personObj.setPhone2(null);
personObj.setEmail(null);
personObj.setState("AZ");
personObj.setLeadDate(null); // Fix Later
personObj.setCompany("Dan's Mortage");
personObj.setCompanyContactName("Indiana Jones");
personObj.setOutsideRep("Joel Martin");
Person personObj2 = new Person();
personObj2.setOrganization("ACC");
personObj2.setFirstName("Richard");
personObj2.setLastName("Nixon");
personObj2.setPhone1(null);
personObj2.setPhone2(null);
personObj2.setEmail(null);
personObj2.setState(null);
personObj2.setLeadDate(null); // Fix Later
personObj2.setCompany("Dan's Mortage");
personObj2.setCompanyContactName("Indiana Jones");
personObj2.setOutsideRep("Joel Martin");
List<Person> personArrayList = new ArrayList<Person>();
personArrayList.add(personObj);
personArrayList.add(personObj2);
PersonList personList = new PersonList();
personList.setPersonList(personArrayList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(personList);
try {
// write converted json data to a file named "PersonList.json"
FileWriter writer = new FileWriter("C:\\Users\\Dylan\\JsonFiles\\PersonList.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"https://myurl/addlist");
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
如果有人可以告诉我一种可以设置我的凭据的方式,那么我就不会收到401错误,或者如果你们能看到导致问题的任何其他因素并且可以让我知道,那就太棒了。提前谢谢。
答案 0 :(得分:1)
您需要在拨打电话之前配置SSL设置。目前,您的POST很可能在SSL握手期间失败。快速解决方法是信任所有证书。这是一个代码片段,它将执行此操作:
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost postRequest = new HttpPost("https://myurl/addlist");
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);