0

So I'm trying to post to a URL (which I can't show, because it's sensitive information), but I keep getting a 401 error, which means unauthorized. And I have credentials, but I don't know how to set them. I have a username, password, and a role.

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();

    }
}
}

If anyone can show me a way where I could set my credentials, so that I won't get a 401 error, or if you guys can see anything else that's causing the issue and could let me know, that would be great. Thanks in advance.

dochsner
  • 249
  • 2
  • 8
  • 25
  • What kind of authentication the service expecting? – seenukarthi Mar 08 '16 at 04:52
  • I'm not sure, how can I tell? This is my first project like this. – dochsner Mar 08 '16 at 04:53
  • All the error says is `reason unauthorized` – dochsner Mar 08 '16 at 04:54
  • 1
    @dochsner, add authentication information to request object. You could see this http://stackoverflow.com/questions/3283234/http-basic-authentication-in-java-using-httpclient – mmuzahid Mar 08 '16 at 04:57
  • You need to configure your SSL settings. In simple terms, either your code or the server is refusing to proceed because of security settings. – Tim Biegeleisen Mar 08 '16 at 05:01
  • @TimBiegeleisen you can't open a connection if the server if refusing the connection because of the ssl settings. If you can't open a connection, you can't receive a response from the server. a 401 error is a response from the server. – njzk2 Mar 08 '16 at 08:04

1 Answers1

1

You need to configure your SSL settings before you make the call. Currently, your POST is failing most likely during the SSL handshake. A quick fix would be to trust all certificates. Here is a code snippet which will do just that:

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • What's the new error? – Tim Biegeleisen Mar 08 '16 at 06:03
  • When I try to put this code in the Eclipse it underlines this line in red `builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());` and says `Unhandled exception type KeyStoreException` – dochsner Mar 08 '16 at 06:05
  • Huh? Are you missing a dependency or something? You will have to resolve this on your own, I believe my strategy is correct for your problem. – Tim Biegeleisen Mar 08 '16 at 06:06
  • I'm using httpclient-4.3.1.jar – dochsner Mar 08 '16 at 06:07
  • I'll work on it, and then accept your answer if it all comes together. – dochsner Mar 08 '16 at 06:08
  • Type `builder.` ... do you see a list of methods come up? Is `loadTrustMaterial()` in that list? – Tim Biegeleisen Mar 08 '16 at 06:08
  • Try adding a new line of code which contains this: `TrustSelfSignedStrategy myStrategy = new TrustSelfSignedStrategy();` ... does that give you an error? – Tim Biegeleisen Mar 08 '16 at 06:13
  • no problem with that one – dochsner Mar 08 '16 at 06:15
  • 1
    Ok, I may have got it – dochsner Mar 08 '16 at 06:18
  • The IDE accepts it, I had to add some more `catch exceptions`, however this is my new error when I run the app – dochsner Mar 08 '16 at 06:20
  • `Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/util/Args at org.apache.http.conn.ssl.SSLConnectionSocketFactory.(SSLConnectionSocketFactory.java:180) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.(SSLConnectionSocketFactory.java:175) at com.brightpatternAPI.GSONBrightPatternPost.main(GSONBrightPatternPost.java:86)` – dochsner Mar 08 '16 at 06:21
  • I just checked your JAR, and `SSLConnectionSocketFactory` is definitely in there. Maybe you are missing an import statement (though Eclipse should handle all of this for you automatically) ? Also, check to make sure the JAR is on your Eclipse classpath. – Tim Biegeleisen Mar 08 '16 at 06:23
  • the OP is receiving a 401. I doubt it has anything to do with SSL. 401 means the connection was successfully established, but the server decided not to let you go through with the request. An SSL related error would have happened way before that. – njzk2 Mar 08 '16 at 07:52
  • @njzk2 The OP is using `https` which requires a certain type of setup. By accepting all certificates, the hope is that he could get his request through. If you have a better idea, why don't you post instead of leaving a comment here? – Tim Biegeleisen Mar 08 '16 at 07:59
  • I already voted to close the question as a duplicate, so I won't add an answer. the ssl handshake is way before the http connection, so the simple fact that the OP receives a response from the HTTP server, not from the SSL layer, should tell you that the ssl configuration is fine. – njzk2 Mar 08 '16 at 08:01
  • Wait...if he's going over `https` how could it possibly be fine unless the server is also accepting all connections (not likely)? – Tim Biegeleisen Mar 08 '16 at 08:02
  • why would an https server not be accepting connections? stackoverflow uses an https server, and they are accepting my connections. It is up to the client to figure if they want to continue talking to the server once they received the certificate and compared it with the list of trusted root certificates. HttpClient relies on the system's root certificates, so in the case of Android, that's most of the common certificates issuers. – njzk2 Mar 08 '16 at 08:07