MultipartEntity Files not uploading through device - java

Possibly this is a duplicate question but I have already tried all answer of this site but none of this working!
I am using MultipartEntity for image upload. It's working completely fine in Emulator but When I check in device its not working.
Below my code
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP);
HttpClient httpClient = new DefaultHttpClient(params);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://url.com/webservice_uploadvideo.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
FileBody filebodyVideopre = new FileBody(new File(videoUploadpathPre)); //pre
entity.addPart("fin_detail", filebodyVideopre);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);

Here's my working code for multi-part image uploading. Yes it works in real device.
private int uploadImage(String selectedImagePath) {
try {
HttpClient client = new DefaultHttpClient();
File file = new File(selectedImagePath);
HttpPost post = new HttpPost(Constants.URL);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
Constants.BOUNDARY, Charset.defaultCharset());
entity.addPart(Constants.MULTIPART_FORM_DATA_NAME, new FileBody(file));
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "multipart/form-data; boundary=" + Constants.BOUNDARY);
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
int status = response.getStatusLine().getStatusCode();
return status;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Related

Is my HTTPClient connection leaking sockets?

I have an app deployed on google app engine that uses the Apache HTTPClient. Recently as the app is getting more traffic, I have started running into exceptions where the sockets quota has been exceeded. The exception is
com.google.apphosting.api.ApiProxy$OverQuotaException: The API call remote_socket.SetSocketOptions() required more quota than is available.
I reached out to the App Engine team and they wanted me to check if my app was leaking sockets.
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.spark.com");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("param1", "val1"));
nvps.add(new BasicNameValuePair("param2", "val2"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
Document doc = null;
try {
HttpEntity entity = response.getEntity();
doc = Jsoup.parse(entity.getContent(), "UTF-8", "");
EntityUtils.consume(entity);
} finally {
response.close();
httpclient.close();
}
This is what my http connection code looks like. Am I doing something wrong which may be causing the sockets to leak? Can I do something better?
this work for me :
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// HttpPost httppost = new HttpPost("http://rafsanjan.uni-azad.my.com/json/darkhasr.php?shdaneshjo="+value_id+"&moavenat="+value_seaction+"&darkhast="+zir_item+"&startdate=test&tozih="+ value_descration); //???
try {
URIBuilder builder = new URIBuilder();
builder.setScheme("http")
.setHost("app.my.ac.com")
.setPort(1180)
.setPath("/json2/darkhasr.php")
.addParameter("shdaneshjo", value_id)
.addParameter("moavenat", value_seaction)
.addParameter("darkhast", value_item)
.addParameter("startdatet", "0")
.addParameter("tozih", value_descration)
.build();
// .fragment("section-name");
String myUrl = builder.toString();
Log.d("url=>",myUrl);
HttpPost httppost = new HttpPost(myUrl);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(8);
//nameValuePairs.add(new BasicNameValuePair("name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.d("RESPONSE",EntityUtils.toString(resEntity));
}
catch(Exception e)
{
Log.e("log_tag", "Error: "+e.toString());
}

multipart request on Android goes to timeout

I Need to upload one file from my Android using multipart and tried with the below code but with no luck.
I got a connection timeout exception and tried with different code having the same result.
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody(USER_ID, "DFD");
entityBuilder.addTextBody(NAME, "DFD");
String filepath = Environment.getExternalStorageDirectory() + "/Download/myImage.jpg";
Log.d(MULTIPART_TAG, filepath);
File file = new File(filepath);
if(file != null)
{
entityBuilder.addBinaryBody("IMAGE", file);
}
HttpEntity entity = entityBuilder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();
}
Here is the exception that I get:
08-06 17:49:03.006: W/System.err(24761): Caused by:
libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed
out)
I also tried with those solutions:
https://stackoverflow.com/a/19188010/1948785
and with the deprecated class MultipartEntity
My second question is what is the meaning of this warning (I dont know if it is related with my problem but I get it when performing the request):
08-06 17:45:53.461: W/dalvikvm(24761): VFY: unable to resolve static
field 3008 (INSTANCE) in
Lorg/apache/http/message/BasicHeaderValueParser;
The libs I am using are those:
httpclient-4.3.4.jar
httpcore-4.3.2.jar
httpmime-4.3.4.jar
Try to set timeout duration of HttpClient.
int TIMEOUT_MILLISEC = 20000; // = 20 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
Try this ,
DefaultHttpClient httpClient = new DefaultHttpClient();
// yourimagefile is your imagefile
HttpPost httpPostRequest = new HttpPost(URL);
// Try This
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPostRequest.setEntity(mpEntity);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Check the size of the image. It might be that the image is too large and it is taking a long period of time to upload and the server is issuing a timeout on that connection.

Java HTTP Post form and file

So I want to use the TestFairy API (url: https://app.testfairy.com/api/upload). This API call expects 3 post paramters:
api_key (string)
apk_file (.apk file)
testers_groups (string)
So far I came up with this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("testers_groups", testers));
params.add(new BasicNameValuePair("api_key", key));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("apk_file", new FileBody(file));
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
But it does not work.
Can anybody point me in the right direction?
Try something like this:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("api_key", new StringBody(key));
entity.addPart("apk_file", new FileBody(file));
entity.addPart("testers_groups", new StringBody(testers));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
Optionally add mime-types in the StringBody and FileBody constructors (but probably not necessary).

Http cookie store in Android

I am developing an Android client for the site with authorization. I have a post method. Example my code:
public void run() {
handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
httpClient = new DefaultHttpClient();
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
HttpResponse response = null;
try{
switch (method){
case POST:
HttpPost httpPost = new HttpPost(url);
httpPost.setHeaders(headers);
if (data != null) httpPost.setEntity(new StringEntity(data));
response = httpClient.execute(httpPost);
break;
}
processEntity(response);
}catch(Exception e){
handler.sendMessage(Message.obtain(handler, HttpConnection.DID_ERROR, e));
}
ConnectionManager.getInstanse().didComplete(this);
}
How to keep cookies?
You get your cookies from HttpResponse response:
Header[] mCookies = response.getHeaders("cookie");
and add them to your next request:
HttpClient httpClient = new DefaultHttpClient();
//parse name/value from mCookies[0]. If you have more than one cookie, a for cycle is needed.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpGet = new HttpGet("http://www.domain.com/");
HttpResponse response = httpClient.execute(httpGet, localContext);

Android post request

I have javascript code that i am trying to mimic in an android application:
Here is the javascript code:
text = '{"username":"Hello","password":"World"}';
x.open("POST", url);
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Content-length", text.length);
x.send(text);
and here is what i have so far for the android application(doesnt work):
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
String text = "\"{\"username\":\"Hello\",\"password\":\"World\"}\"";
httppost.setHeader("Content-length",Integer.toString(text.length()));
httppost.setEntity(new StringEntity(text));
HttpResponse response = httpclient.execute(httppost);
when i try to debug this code on eclipse the emulater keeps running while the debugger hangs. Thanks!
Note: its hanging on httpclient.execute(httppost)
Here is the code I use for Android post requests:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("fullurl");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("parameter", "variable");
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
...and so on.
Try it out:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
JSONObject json = new JSONObject();
try{
json.put("username", "Hello");
json.put("password", "World");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
}
Did you mean to set your HttpPost path to just path. I think your hanging because you haven't given the HttpPost a valid URL. You'll need to modify this line:
HttpPost httppost = new HttpPost("path");
to something like
HttpPost httppost = new HttpPost("actual/url/path");
You have extra speech marks within the start and end of your text string compared to the JS version?
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(StringUrl);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println("rep => " + response);
} catch (IOException e) {
System.out.println(e);
}
}

Categories

Resources