PUT Gives 406 Not Acceptable

Gardenofsyed
New Member
6 0 0

Hi, 

I am getting '406 Not Acceptable' when i use PUT request for product update using Java Http Client.

Here is my data,

{"product":{"id":5249777565859,"title":"032C Issue 37"}}

 

I set the headers as "Content-Type", "application/json"

 

Please kindly help me to solve this issue. 

0 Likes
Greg_Kujawa
Shopify Partner
1016 83 237

You sure that your client is issuing a PUT request and not a POST request?

0 Likes
Gardenofsyed
New Member
6 0 0
Hi Greg,

Confirm I am using PUT.. I tested Postman working fine, but not from Apache
httpclient httpput not working.

Tried httpUrlConnection also giving the same response code.

I couldn’t find solution on internet.

Please kind help me to solve this problem.

I am using Content-Type as application/json on header, and using Gson to
convert object to Json. Did I missing anything on headers other than
content type.

Thank you


0 Likes
Greg_Kujawa
Shopify Partner
1016 83 237

If you can share a sanitized code sample, along with a packet capture, that might help others see what's going on in terms of your issue. If Postman is working and your Apache client isn't then that client must be hitting the snag. That's why the code sample and packet capture will shed some more light...

0 Likes
Gardenofsyed
New Member
6 0 0

Hi Greg, 

This is my code,

String block = "{\"id\":" + id + ",\"title\":\"" + titleStr + "\"}";

 

        StringBuilder entity = new StringBuilder();

        entity.append("{");

        entity.append("\"product\":" + block );

        entity.append("}");

HttpPut httpPut = new HttpPut(url);

        httpPut.addHeader("Content-Type", "application/json");

        httpPut.setHeader("Accept", "application/json");

       StringEntity se = new StringEntity(entity,HTTP.UTF_8);

        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        httpPut.setEntity(se);

try (CloseableHttpClient httpClient = HttpClientBuilder.create()

                .setDefaultCredentialsProvider(provider)

                .build();

             CloseableHttpResponse response = httpClient.execute(httpPut)) {

            // 401 if wrong user/password

        Header[] headers = response.getAllHeaders();

            for (Header header: headers) {

                System.out.println("Key [ " + header.getName() + "], Value[ " + header.getValue() + " ]");

            }

            HttpEntity resEntity = response.getEntity();

            if (entity != null) {

                // return it as a String

                result = EntityUtils.toString(resEntity);

                System.out.println(result);

            }

        }

0 Likes
Greg_Kujawa
Shopify Partner
1016 83 237

I don't see where you are setting the auth credentials in the header. Unless I'm just not looking at things right. If it were me, I would use Fiddler to capture the API request you are sending from both Postman and your Apache web client. Then you can look at the request body, the request headers, etc. and arrive at the root cause of the Apache web client side issue.

0 Likes
Gardenofsyed
New Member
6 0 0

Not only Apache HTTP Client give error, but also HttpUrlConnection also give the same error, 

I'm using basic authentication when creating the connection, and I can execute GET request.

 

This is code snippet using Java 8 HttpURLConnection..

 

String url = "https://" + store.getStoreName() + "/admin/api/2020-10/5249777565859.json";

HttpURLConnection con = getHttpConnection(url,store.getApiUserName(), store.getApiPasswd(), "PUT");

String str = "{\"id\":" + 5249777565859L + ",\"title\":\"" + resDto.getTitle() + "\"}";

String jsonString = "{\"product\":"+ str + "}";

System.out.println(" Product Value * " + new Gson().toJson(product));

System.out.println("Status : "+con.getRequestMethod() + " Type : "+con.getRequestMethod());

//String postJsonData = new Gson().toJson(map);

con.addRequestProperty("Content-Length", Integer.toString(jsonString.getBytes().length));

OutputStream outputStream = new BufferedOutputStream(con.getOutputStream());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));

        writer.write(new Gson().toJson(product).toString());

        writer.flush();

        writer.close();

        outputStream.close();            

 

        con.connect();

        System.out.println("After Connect: ");

int responseCode = con.getResponseCode();

System.out.println("nSending 'PUT' request to URL : " + url);

System.out.println("Response " + con.getResponseMessage());

System.out.println("Response Code : " + responseCode);

 

 

My Connection Details:

 

public  HttpURLConnection getHttpConnection(String url, String apiUserName, String apiPassword ,String type){

        URL uri = null;

        HttpURLConnection con = null;

        try{

            uri = new URL(url);

            con = (HttpURLConnection) uri.openConnection();

            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET

            String basicAuth = "Basic " + Base64.getEncoder().encodeToString((apiUserName + ":" + apiPassword).getBytes());

    con.setDoOutput(true);

            con.setDoInput(true);

            //con.setConnectTimeout(60000); //60 secs

            //con.setReadTimeout(60000); //60 secs

            con.setRequestProperty("Content-Type", "application/json");

            con.setRequestProperty("Authorization", basicAuth);

            //con.setRequestProperty("Accept", "*/*");

            //con.setRequestProperty("User-Agent", "request");

        }catch(Exception e){

            //logger.info( "connection i/o failed" );

        e.printStackTrace();

        }

        return con;

}

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

StringBuffer respose = new StringBuffer();

String line="";

while ((line = in.readLine()) != null) {

respose.append(line);

}

in.close();

// printing result from response

System.out.println(respose.toString());

con.disconnect();

0 Likes
Greg_Kujawa
Shopify Partner
1016 83 237

I don't have an environment to replicate this on my end, but sometimes isn't the HTTP 406 error due to there being a failure to negotiate the call between client and server? Particularly the Accept header values the client is sending versus what values the server can work with. That's why I was suggesting capture and inspect all of the request and response headers. Compare what works in Postman versus what's not working with your Apache client and whatnot. I'd be willing to wager that the request headers in Postman aren't what appear in your other client attempts. 

0 Likes
Gardenofsyed
New Member
6 0 0

When i compare Postman, with the http client request headers, postman adds few headers like "Cookies","Postman-Token","Host", "Content-Length". I really do not find the the required headers except "Content-Type" to be added to the http client request. Also, I couldn't find any good java code examples for Shopify Api. It makes developer life bit difficult while implementation. 

I'm calling the PUT request from my development environment (localhost..).. I do not know is there any api restriction for localhost. 

It would be easier if i get any java code examples. 

Thank you. 

 

Here is my response header,

 

07:14:00,390 INFO  [stdout] (default task-52)  JSON : {"product":{"id":5249777565859,"title":"032C Issue 37"}}

07:14:00,395 INFO  [stdout] (default task-52) Hibernate: select webstore0_.storecode as storecod1_333_, webstore0_.accesskey as accesske2_333_, webstore0_.apipasswd as apipassw3_333_, webstore0_.apiurl as apiurl4_333_, webstore0_.apiusername as apiusern5_333_, webstore0_.authtype as authtype6_333_, webstore0_.createdby as createdb7_333_, webstore0_.datecreated as datecrea8_333_, webstore0_.dateupdated as dateupda9_333_, webstore0_.storename as storena10_333_, webstore0_.updatedby as updated11_333_, webstore0_.vendorcode as vendorc12_333_ from nexgen.webstore webstore0_ where webstore0_.storecode=?

07:14:00,396 INFO  [stdout] (default task-52)  URL https://basheer-webstore.myshopify.com/admin/api/2020-10/5249777565859.json

07:14:01,006 INFO  [stdout] (default task-52)  Response : HTTP/1.1 406 Not Acceptable

07:14:01,006 INFO  [stdout] (default task-52) Key [ Date], Value[ Mon, 14 Dec 2020 23:14:01 GMT ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ Content-Type], Value[ application/json ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ Transfer-Encoding], Value[ chunked ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ Connection], Value[ keep-alive ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Sorting-Hat-PodId], Value[ 194 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Sorting-Hat-ShopId], Value[ 11057032 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ Referrer-Policy], Value[ origin-when-cross-origin ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Frame-Options], Value[ DENY ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-ShopId], Value[ 11057032 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-ShardId], Value[ 194 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Stats-UserId], Value[  ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Stats-ApiClientId], Value[ 4203013 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Stats-ApiPermissionId], Value[ 272578379939 ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ X-Shopify-API-Terms], Value[ By accessing or using the Shopify API you agree to the Shopify API License and Terms of Use at https://www.shopify.com/legal/api-terms ]

07:14:01,007 INFO  [stdout] (default task-52) Key [ HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT], Value[ 1/40 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Shopify-Shop-Api-Call-Limit], Value[ 1/40 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Shopify-API-Version], Value[ 2020-10 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ Strict-Transport-Security], Value[ max-age=7889238 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Shopify-Stage], Value[ production ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ Content-Security-Policy], Value[ default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; frame-ancestors 'none'; img-src 'self' data: blob: https:; script-src https://cdn.shopify.com https://cdn.shopifycdn.net https://checkout.us.shopifycs.com https://js-agent.newrelic.com https://bam.nr-data.net https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://js.braintreegateway.com https://c.paypal.com https://maps.googleapis.com https://www.google-analytics.com https://v.shopify.com https://widget.intercom.io https://js.intercomcdn.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin_api&source%5Buuid%5D=2407cd75-288e-4e07-b91d-2a2fcc83c036 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Content-Type-Options], Value[ nosniff ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Download-Options], Value[ noopen ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Permitted-Cross-Domain-Policies], Value[ none ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-XSS-Protection], Value[ 1; mode=block; report=/xss-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin_api&source%5Buuid%5D=2407cd75-288e-4e07-b91d-2a2fcc83c036 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Dc], Value[ gcp-asia-southeast1,gcp-us-central1,gcp-us-central1 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ X-Request-ID], Value[ 2407cd75-288e-4e07-b91d-2a2fcc83c036 ]

07:14:01,008 INFO  [stdout] (default task-52) Key [ CF-Cache-Status], Value[ DYNAMIC ]

07:14:01,009 INFO  [stdout] (default task-52) Key [ cf-request-id], Value[ 07052151ba0000d9e863199000000001 ]

07:14:01,009 INFO  [stdout] (default task-52) Key [ Expect-CT], Value[ max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" ]

07:14:01,009 INFO  [stdout] (default task-52) Key [ Server], Value[ cloudflare ]

07:14:01,009 INFO  [stdout] (default task-52) Key [ CF-RAY], Value[ 601b9e62c8cfd9e8-SIN ]

 

0 Likes
Gardenofsyed
New Member
6 0 0

Finally, I solved this issue. Actually the endpoint missing "products", which causes the problem. Thank you very much for your kind support. 

0 Likes