2

I am trying to send a POST request with some String parameters and a jpeg image file. The whole code is in an IntentService.

I am using an Authorization header for the basic auth (the credentials work when using them with another web service).

I can't really get what is wrong, maybe a faulty request property. Keep in mind that I am sending Strings, but also an image.

 int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { FileInputStream fileInputStream = new FileInputStream(new File(filePath)); URL url = new URL(urlServer); String credentials = "[email protected]"+":"+"testtest"; final String basicAuth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestProperty("Content-Type", "multipart/form-data"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes("imei="+ getImei() + "&id=38" + "&type = b" + "&step=1" + "&image=" ); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; int sentBytes = 0; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { mBuilder.setProgress(100,(int) (sentBytes * 100 / bytesAvailable),false); mNotifyManager.notify(1, mBuilder.build()); outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); sentBytes += bufferSize; bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } mBuilder.setContentText("Upload complete"); mBuilder.setProgress(0, 0, false); mNotifyManager.notify(1, mBuilder.build()); fileInputStream.close(); outputStream.flush(); outputStream.close(); if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){ url = new URL(connection.getHeaderField("Location")); connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("Authorization", basicAuth); } InputStreamReader isr = null; BufferedReader reader = null; StringBuilder sb = new StringBuilder(); String line = ""; isr = new InputStreamReader( connection.getInputStream()); reader = new BufferedReader(isr); line = reader.readLine(); while (line != null) { sb.append(line); try { line = reader.readLine(); }catch (Exception e){ line = null; } } String a; a = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); } 
2
  • Try using DefaultHttpClient Commented Aug 11, 2015 at 5:33
  • 401 error need not definitely be because you have sent the username or password wrong. It could also be because of wrong encoding. Commented Aug 11, 2015 at 5:34

1 Answer 1

0

Try using DefaultHttpClient as follows. Instead of Base64.encodeToString, try UsernamePasswordCredentials as below. Even I used POST method with basic auth and it worked.

private HttpResponse getWebServiceResponse(String URL, ArrayList <NameValuePair> params) { HttpResponse httpResponse = null; try { HttpParams httpParameters = new BasicHttpParams(); // Set httpParameters like timeout etc. here. // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); httpClient.getCredentialsProvider().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials("USERNAME", "PASSWORD")); HttpPost httpPost = new HttpPost(URL); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); } catch (UnsupportedEncodingException e) { } httpResponse = httpClient.execute(httpPost); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; } 
Sign up to request clarification or add additional context in comments.

2 Comments

And can you tell me how to send image as NameValuePair?
Please check the accepted answer in stackoverflow.com/q/9212082/3492139 to send an image as name value pair.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.