I'm new to http file transfer. I want to send a file from android sdcard to server. For that i tried the below code. I converted the bytes to json string and sent it to the server. But I'm unable to receive it on the server side. I'm using jsp on server side. But there should be some efficient way to do this. Please provide me some ideas.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
jsp
<%
String value = request.getParameter("wavfil");
byte[] wavByte = value.getBytes();
FileOutputStream fos = new FileOutputStream("/TESTFILE.wav");
fos.write(wavByte, 0, wavByte.length);
if (wavByte != null) {
out.println("Success");
} else {
out.println("Failed");
}
%>
Add below lines
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.x.x.x:8084/httptest");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String encodedString = convertURL(jsonString);
nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Create and attach file to the Post
File file = new File("pathto your file"); //replace with actual path
MultipartEntity entity = new MultipartEntity();
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
entity.addPart("file", new FileBody(file));
if (entity != null) {
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
tv.setText(responseString);
Log.d("HTTP LOG", responseString);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Related
I am calling a url by following method
try {
urlcont= URLEncoder.encode(urlcont, "utf-8");
response = CustomHttpClient.executeHttpGet("http://www.myurlhere");
} catch (Exception e) {
e.printStackTrace();
}
URL called successfully but I want to post some data (in String urlcont ) so i can get it by $_POST['urlcont'];
Thanks
try this
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("name", "your name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I'm trying to make a POST request to a server in my Android app, but it ain't happening. Below is the code -
try{
View p = (View) v.getRootView();
EditText usernamefield = (EditText)p.findViewById(R.id.username);
String username = usernamefield.getText().toString();
EditText passwordfield = (EditText)p.findViewById(R.id.pass);
String password = passwordfield.getText().toString();
String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";
Log.i(TAG,password);
String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();
Log.i(TAG,authToken);
HttpClient client = new DefaultHttpClient();
Log.i(TAG,"after client1");
HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
Log.i(TAG,"after client2");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i(TAG,post.getURI().toString()); //logs the URL
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
Log.i(TAG,"Status code is"+status);
Log.i(TAG,"after post");
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
{
Log.i(TAG,"bad http response");
Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
System.out.print(sb.toString());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NoSuchAlgorithmException e)
{
}
catch(Exception e){
}
The code executes till the Log.i(TAG,post.getURI().toString()) log statement. It'll print out the URL that is made - http://ws.audioscrobbler.com/2.0/. No parameters attached (which is weird).
I don't know what's wrong with my implementation for adding parameters to URL using NameValuePairs.
I do have one simple method to post data to server. Please use it and let me know if that is useful to you or not:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");
public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
url = url.trim();
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpPost httpPost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
You must have wrapped this code in a try catch block since there are several possible exceptions thrown here. As to which is the problem I am not sure, but here are some common ones that could cause a problem and you need to give more info before we can see which one it is:
1) On newer versions of Android if you make thisw call in the main UI thread it will throw an exception a NetworkOnMainThread exception. You must do networking code on a background thread.
2) You did not declare the Internet permission in your manifest so it will throw a security exception.
You need to look at the logcat for an exception or break in the catch part of your try/catch. If your catch looks like this:
catch(Exception e)
{
}
Then it will silently eat the exception and give you no indication of the problem.
Just try with JsonStringer.Like:
HttpPost request = new HttpPost("http://ws.audioscrobbler.com/2.0/something_here");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("method")
.value("auth.getMobileSession").key("api_key").value(apikey)
.key("api_sig") .value(authSig).key("format").value("json").key(authToken).value(authToken).key("username").value(username)
.endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Also as Kaediil said make try and catch clause with your response code.
Hi I want to send a json object to a web service , I have tried almost everything without success. When the webservice recives the data it returns "eureka" , so I want to be able to see the response too.
public void sendData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=");
try {
httppost.setEntity(new UrlEncodedFormEntity(json));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
private void SendBookingData(final String SendCustomerId,final String SendCustomerName, final String BookingDate,
final String BookingTime, final String SendNetAmount,final String SendTotalAmount, final String SendTotalQuantity,
final String SendDeliveryDate, final String GetBranchId,final String Senduserid,final String Sendratelistid) {
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
String SendBookingURL= "your url";
HttpPost post = new HttpPost(SendBookingURL);
HttpResponse response;
json.put("GetcustomerName", SendCustomerName);
json.put("GetBookingDate",BookingDate);
json.put("GetTotalCost", SendTotalAmount);
json.put("GetNetAmount", SendNetAmount);
json.put("GetTotalQuantity",SendTotalQuantity );
json.put("GetCustomerId", SendCustomerId);
json.put("GetDeliveryDate", SendDeliveryDate);
json.put("GetBookingtime", BookingTime);
json.put("GetBranchId", GetBranchId);
json.put("GetUserId", Senduserid);
json.put("GetRateListId", Sendratelistid);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
try {
response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity != null) {
ResponseSummaryTable = EntityUtils.toString(entity);
System.out.println("body" + ResponseSummaryTable);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Send string entity instead
CODE:
HttpClient client = new DefaultHttpClient();
HttpUriRequest request;
request = new HttpPost(<-URL->);
StringEntity entity = new StringEntity(<-Your JSON string->);
((HttpPost) request).setEntity(entity);
((HttpPost) request).setHeader("Content-Type",
"application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
This code will send json as string entity to server and receives HttpEntity as response
I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, String taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}
My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;