I have to upload file to server whose API is a PUT request of content type as application/octet-stream. Below is my code
private void uploadVideo(File binaryFile, String url) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPut put = new HttpPut(url);
FileEntity reqEntity = new FileEntity(binaryFile, "application/octet-stream");
reqEntity.setContentType("application/octet-stream");
put.setEntity(reqEntity);
HttpResponse response = httpclient.execute(put);
HttpEntity entity = response.getEntity();
Log.d("INFO", "rcode:" + response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() - 200 >= 100)
throw new Exception("bad status code: " + response.getStatusLine().getStatusCode());
String responseString = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
I keep getting bad request but when I try from postman the file uploads perfectly fine. Any solutions?
bad status code: 400
I am using the following code to download file and calculate the length but the return value(length) is always -1
private long getContentLength(String url) {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
System.out.println("Content length was: " + httpEntity.getContentLength() + " and code: " + httpResponse.getStatusLine().getStatusCode());
return httpEntity.getContentLength();
}
The file being downloaded:
boolean download100MBFile() {
getContentLength("http://cachefly.cachefly.net/100mb.test");
return true;
}
The HTTP response code is: 200
The file gets downloaded from the browser, so there is no issue with the file. What is going wrong here?
The comment by Victor sparked me to use a stream.
Here is the updated code which works:
private long getContentLength(String url) {
outputStream.reset();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception ex) {
logException(ex);
return -1;
}
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null)
return -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024 * 1024 * 1024);
try {
httpEntity.writeTo(outStream);
} catch (IOException ex) {
logException(ex);
return -1;
}
return outStream.size();
}
Hi this is the web method to receive JSON and response JSON but the problem is this web method doesn't accept the gzip encoded request so how to make it to gzip acceptable web method?
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/pdf2doc")
public RPDOC postDocument(DPDF dpdf){
}
DPDF is the class
public class DPDF{
public String docid;
public String pdfdata;
}
This the client code with gzip Content encoding and throw exeption
String body = "{\"docid\": 1234, \"docdata\": \"test\"}";
HttpEntity httpEntity = EntityBuilder.create().setText(body)
.setContentEncoding("gzip")
.gzipCompress().build();
final String postUrl = serviceURL;
HttpUriRequest request = RequestBuilder.post(postUrl)
.setHeader(HttpHeaders.CONTENT_TYPE,
"application/json")
.setHeader(HttpHeaders.ACCEPT,
"application/json")
.setEntity(httpEntity)
.build();
String sResponse = null;
try (CloseableHttpClient httpclient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpclient.execute(request))
{
StatusLine sl = response.getStatusLine();
int statusCode = sl.getStatusCode();
System.out.println("HTTP Status: " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null)
{
sResponse = EntityUtils.toString(entity).trim();
System.out.println("HTTP Body:\n" + sResponse);
EntityUtils.consumeQuietly(entity);
}
}
catch (Exception e)
{
request.abort();
throw e;
}
}
catch (Exception e)
{
e.printStackTrace();
}
I've been trying to get a simple android client server app working, and I've had nothing but trouble. I'm hoping someone can look at this code and see what I'm doing wrong, maybe I'm doing things in the wrong order, or forgetting something? Just adding the relevant parts
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/json");
// set some made up parameters
String str = "{'login':'superman#super.com','password':'password'}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
// connection.setDoOutput(true); //should trigger POST - move above -> crash
conn.setRequestMethod("POST"); // explicitly set POST -move above so we can set params -> crash
conn.setDoInput(true);
The error I get is
'exception: java.net.ProtocolException: method does not support a
request body: GET'
If I just do a POST request without parameters it's fine, so I guess I should move the connection.setDoOutput(true); or conn.setRequestMethod("POST"); higher up, that should work right? When I do that I get the error:
exception: java.net.ProtocolException: Connection already established.
So, if I try to set to POST before adding parameters it doesn't work, if I try to do it after it doesn't work... what am I missing? Is there another way I should be doing this? Am I adding parameters incorrectly? I've been searching for a simple android networking example, and I can't find any, is there any example the official Android site? All I want to do is a very basic network operation, this is so frustrating!
EDIT: I need to use HttpsURLConnection for reasons not included in the above code- I need to authenticate, trust hosts, etc- so I'm really looking for a potential fix for the above code if possible.
Here is an example of how to post with a JSON Object:
JSONObject payload=new JSONObject();
try {
payload.put("password", params[1]);
payload.put("userName", params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
String responseString="";
try
{
HttpPost httpPost = new HttpPost("www.theUrlYouQWant.com");
httpPost.setEntity(new StringEntity(payload.toString()));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = new DefaultHttpClient().execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
And example of how to get
String responseString = "";
//check if the username exists
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.theUrlYouQWant.com");
ArrayList<String> existingUserName = new ArrayList<String>();
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
else
{
Log.e(ParseException.class.toString(), "Failed to download file");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I followed this tutorial on making http calls:
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Works fine with no problems.
Below is a class that I have modified from the sample:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
String TAG = ((Object) this).getClass().getSimpleName();
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
*/
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
*/
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 2000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
Log.e("Request: ", "> " + url);
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
if (httpResponse != null) {
httpEntity = httpResponse.getEntity();
} else {
Log.e(TAG, "httpResponse is null");
}
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
And this is how I use the class:
nameValuePairs = new ArrayList<NameValuePair>();
String param_value = "value";
String param_name = "name";
nameValuePairs.add(new BasicNameValuePair(param_name, param_value));
// Creating service handler class instance
sh = new ServiceHandler();
String json = sh.makeServiceCall(Utils.getUrl, ServiceHandler.GET, nameValuePairs);
I am creating a httpClient and I want to add certain header to my HttpGet request
My current code produces the following request.
GET /folder/index.html HTTP/1.0
Host: localhost:4444
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
What I want is to add another header (If-Modified-Since) in that request .
How can I do it?
Thank you :)
public String httpGet(String s) {
String url = s;
StringBuilder body = new StringBuilder();
httpclient = new DefaultHttpClient(); // create new httpClient
HttpGet httpGet = new HttpGet(url); // create new httpGet object
try {
response = httpclient.execute(httpGet); // execute httpGet
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// System.out.println(statusLine);
body.append(statusLine + "\n");
HttpEntity e = response.getEntity();
String entity = EntityUtils.toString(e);
body.append(entity);
} else {
body.append(statusLine + "\n");
// System.out.println(statusLine);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection(); // stop connection
}
return body.toString(); // return the String
}
Use the setHeader() method on the HttpGet object like follows.
httpGet.setHeader("If-Modified-Since","11/26/2012");
I used this JavaDoc as a reference.
Use the setHeader() method on the HttpGet object like follows for the first one
httpGet.setHeader("If-Modified-Since","11/26/2012");
and then use addHeader() method on the HttpGet object like as follows for the second header.
httpGet.addHeader("If-Expires-On","11/26/2014");