The AsyncHttpClient version is 1.4.7.
The server recieves the request, but could not find the file param
Working example
HttpClient httpclient;
HttpPost httppost;
httpclient = new DefaultHttpClient();
httppost = new HttpPost(URLRepo.URL_IMAGESAVE);
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id", ""+deichapp.getInt("userid", 0)));
//.. add parameters
File file = new File(new URI(obj.getString("fileUri")));
nameValuePairs.add(new BasicNameValuePair("filename", file.getName()));
httpclient.getParams().setParameter("Connection", "Keep-Alive");
httpclient.getParams().setParameter("Content-Type", "multipart/form-data;");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
for (BasicNameValuePair nameValuePair : nameValuePairs) {
entity.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
}
entity.addPart("file", new FileBody(new File(new URI(obj.getString("fileUri")))));
httppost.setEntity(entity.build());
// Send and store the Image
HttpResponse response = httpclient.execute(httppost);
String json;
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
This uses the native android api and no external librarys like async http client. Make sure you execute this code on a background thread.
Try this:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
Hope this helps!
Related
I need to upload image file on Server using HttpGet Method.Please help me out.
Thanks
use http post request ...convert image to byte array and then send it to server
InputStream is = this.getAssets().open("image.png");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest =
new HttpPost("http://webserver.com/doSomething.do");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new
ByteArrayInputStream(data), "uploadedFile");
StringBody sb1 = new StringBody("some text goes here");
StringBody sb2 = new StringBody("some text goes here too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse response =httpClient.execute(postRequest);
response.getEntity().getContent().close();
As already hinted by Nitesh, in order to upload image file you should use a Post request and submit your file as binary.
Please refer below link in SO for more details:
How do I send a file in Android from a mobile device to server using http?
Try this
String _URL =https://194.1.3.9:7721/request?image_byte=iamge _inbyte;
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(_URL);
HttpResponse response = client.execute(request);
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
I have a problem in posting the data to server by using httpput methods in android.I have to send feedback to server and getting json response. but i am getting 404 bad request. but i dont know where is the problem.
I am strucked here and didn't find any solution. Any suggestions?
My code is as follows:
HttpClient client = new DefaultHttpClient();
HttpPut put = new HttpPut(getString(R.string.feedBack));
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("userId", "8"));
pairs.add(new BasicNameValuePair("feedback",feedbackMessage
.getText().toString()));
put.addHeader("Content-Type", "application/json");
put.addHeader("Accept", "application/json");
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
Log.d(tag, "Result" + response.getStatusLine());
You are not initializing a URL object and passing in simple String.
You should do this instead:
URL url = new URL(getString(R.string.feedBack));
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
And it should work.
I've been trying this for the best part of two weeks now, and I am really stuck. Initially I had created a simple ObjectOutputStream client - server program - with the client being the Android app, but it does not work (it reads the connection but not the object).
So now I am confused as to what other approaches I might be able to take to carry out this simple task? Can anyone Help?
have you tried URLConnection using post method? :)
Or get method like:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
you can try JSON stirng to send data. We have a lot of stuff available on how to work with JSON and also there are many api's. JSONSimple is the one I can suggest. Its really easy.
why don't you try this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
You can use this to post an Entity to server:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
An Entity can be name value pair:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
Or you can send an entity with bytearray.
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
If you want to post json to server:
Please check out this link How do I send JSon as BODY In a POST request to server from an Android application?
For serializing and deserializing java object, I recommend https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Really hope it can help you see an overview of sending data to server
I am developing a hotel booking app using expedia. I need to send the following rest data to server using the httppost
http:/api.ean.com/ean-services/rs/hotel/v3/list?minorRev=[current minorRev #]
&cid=55505
&apiKey=xxx-yourOwnKey-xxx
&customerUserAgent=xxx
&customerIpAddress=xxx
&locale=en_US
¤cyCode=USD
&city=Seattle
&stateProvinceCode=WA
&countryCode=US
&supplierCacheTolerance=MED
&arrivalDate=09/04/2012
&departureDate=09/05/2012
&room1=2
&numberOfResults=1
&supplierCacheTolerance=MED_ENHANCED
String urlToSendRequest = "https://example.net";
String targetDomain = "example.net";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(targetDomain, 80, "http");
HttpPost httpPost = new HttpPost(urlToSendRequest);
httpPost.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(targetHost, httpPost);
Reader r = new InputStreamReader(response.getEntity().getContent());
Can anyone give me a HTTP PUT request example code for Android?
Assuming you want to use an HttpURLConnection, to perform an HTTP PUT you use the following:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Data you want to put");
out.close();
To use the HTTPPut class then try:
URL url = new URL("http://www.example.com/resource");
HttpClient client = new DefaultHttpClient();
HttpPut put= new HttpPut(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key1", "value1"));
pairs.add(new BasicNameValuePair("key2", "value2"));
put.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(put);
I'm pretty sure this should work though I haven't tested it :)
It's better to use a library like Android Async HTTP or Volley that take the complexity out of networking and make it easier to handle request responses. This is how you would do it with AsyncHTTP:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("some_key", "value-1");
params.put("another_key", "value-2");
client.put(url, params, new AsyncHttpResponseHandler {
public void onSuccess(int statusCode, Header[] headers, String response) {
// Do something with response
}
});