I have huge json data to upload on server, but when I upload using HttpPost getting SocketTimeout Exception, while I changed timeout to 25000 and more.
Does anyone has solution for it?
Does MultiPartEntity will help me in this case ?
If yes then how to send json data on server using MultiPartEntity?
Yes MultiPartEntry from Apache MIME can help you in this case. It is sometimes used for uploading images with some contextual data in multiple parts.
For sending Json you can do something like this
You will have to use MultipartEntityBuilder to create MultipartEntity object.
//use builder as MultipartEntity is deprecated
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String yourJsonString = yourJSONObject.toString();
builder.addPart("key_to_yourJsonString", yourJsonString ); //set your Json String
HttpEntity entity = builder.build(); //create entity
httppost.setEntity(entity);
response = httpClient.execute(httppost);
you would require httpclient.jar, httpcore.jar, httpmime.jar, httpclient.jar, commons-codec.jar and commons-logging.jar to be in classpath.
Refer the below links for more info on this.
bethecoder MultipartEntityDeprecated
Related
I was following this tutorial to upload images with android: here
After the line conn.setRequestProperty("uploaded_file", fileName); in function uploadFile(String sourceFileUri) I added further lines with conn.setRequestProperty("title", "example"); conn.setRequestProperty("name", "simple_image"); but in the php file I am not receiving these strings with $_POST or $_GET only the image is uploaded.
Is this tutorial here only for uploading images?
I would like to send with the image some other data too. How could I do this?
Thank you
Yes that tutorial is for uploading a single file only.If you want to send some other data(may be some strings) along with your image, then you can use MultipartEntityBuilder.However to use this you need to download the jars from the Apache HttpComponents site and add them to project and path(just add the httpclient jar to your libs folder).
Now for uploading an image along with some string data you can use (may be inside doInBackground of your AsynTask)
File file = new File("yourImagePath");
String urlString = "http://yoursite.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
/* adding an image part */
FileBody bin1 = new FileBody(file);
builder.addPart("uploadedfile1", bin1);
builder.addPart("user", new StringBody("Some String",ContentType.TEXT_PLAIN));//adding a string
HttpEntity reqEntity = builder.build();
post.setEntity(reqEntity);
HttpEntity resultEntity = httpResponse.getEntity();
String result = EntityUtils.toString(resultEntity);
P.S : I assumed you are using AsyncTask for uploading process and that's the reason i said to use this code inside doInBackground of your AsyncTask.
You can use MultipartEntity too.Follow this tutorial which describes how to upload multiple images along with some other string data using MultipartEntity.However there's not much difference in the implementation of MultipartEntity and MultipartEntityBuilder.Try yourself to learn both.Hope these info help you.
I am trying to fetch current user info after making him log into his box, using the box sdk for android. In the box api documentation, they have mentioned everything using curls. I am not familiar with curl. So, can anyone please give me a java equivalent for this curl operation :
curl https://api.box.com/2.0/users/me-H "Authorization: Bearer ACCESS_TOKEN".
I have the users access token.So, please give me a java equivalent for the above curl operation.
You can use java HttpClient
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Authorization", "Bearer ACCESS_TOKEN"); // add headers if needded
//set params
BasicNameValuePair[] params = new BasicNameValuePair[] {new BasicNameValuePair("param1","param value"),
new BasicNameValuePair("param2","param value")};
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity( Arrays.asList(params), "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
//execute request
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity); //here response in string you can parse it
The HttpClient object that the other answer proposes is now deprecated. I solved a CURL problem like yours (with the extra difficulty of uploading a .wav file). Check out my code in this this answer/question. How to upload a WAV file using URLConnection
I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)
I'm trying to send some json data from Android to a clojure/compojure server
However I can't seem to able to properly send or receive the data, and I'm not quite sure if the problem lies with Android or compojure.
Here is the java code
String PATH = "http://localhost:8080/get_position";
DefaultHttpClient mClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(PATH);
HttpResponse response;
httpget.getParams().setParameter("measurements", measurements.toString());
response = mClient.execute(httpget);
HttpEntity entity = response.getEntity();
Where mesurements is the JSON object.
And the main compojure code for handling the routing
(defroutes main-routes
(POST "/get_position" {params :params}
(emit-json (find-location (:results (read-json (:measurements params))))))
(route/not-found "Page not found"))
The request is properly received, but I get an error that params is nil
java.lang.IllegalArgumentException: No implementation of method: :read-json-from of protocol: #'clojure.data.json/Read-JSON-From found for class: nil
Does anyone see a problem with this code or knows the correct way to do this?
The params map has strings as keys, I believe, not keywords.
I recommend using ring-json-params.
I am new to android networking and would like to find the best solution/source that would help me learn the same. I have a working android application but i want to include network services that can get and send data to the webserver. While i was searching for the same i found link ( http://www.helloandroid.com/tutorials/connecting-mysql-database ) which dont produce any results. I also found that SOAP or REST (with android) are probably recommended methods, if so please give complete tutorials to learn the same ( i have no prior knowledge on webservices). In my application I would be required to send data to the server and receive data from the servers sql
Thank you
This is for post data on server,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// get response entity
HttpEntity entity = response.getEntity();
// convert entity response to string
if (entity != null)
{
InputStream is = entity.getContent();
// convert stream to string
result = convertStreamToString(is);
result = result.replace("\n", "");
}
or see how to post data to remote server in android app [closed], Post the data to Server