Trying to send file content to server from Android application like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
final InputStreamEntity reqEntity = new InputStreamEntity(
gdFileSystemDelegate.openFileInput(openFileInput(FilePath), -1);
reqEntity.setContentType("application/octet-stream");
httppost.setEntity(reqEntity);
httpClient.execute(httppost);
But its throws an exception:
cannot retry request with a non-repeatable request entity
What does it mean ? how to fix that ?
Try to set protocol param http.protocol.expect-continue to true in DefaultHttpClient:
#Override
protected HttpParams createHttpParams() {
HttpParams params = super.createHttpParams();
HttpProtocolParams.setUseExpectContinue(params, true);
return params;
}
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 want to send the below JSON request to a web service and read the response.
{"Email":"aaa#tbbb.com","Password":"123456"}
I know to how to read JSON. The problem is that the above JSON object must be sent in a variable name json.I want to send Json object as a parameter with get request.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet httpget = new HttpGet(FinalURL.toString());
//HttpPost request = new HttpPost(serverUrl);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
You can set request using:
httpget.setEntity(new JSONObject(requestString));
One of the options i'm using right now is RequestParams:
It can be implemented as:
RequestParams rp = new RequestParams();
rp.put("Email", "aaa#tbbb.com");
rp.put("Password", "123456");
Utils.client.get(url, rp, new AsyncHttpResponseHandler() {
//or your http code
http://loopj.com/android-async-http/doc/com/loopj/android/http/RequestParams.html
http://loopj.com/android-async-http/
So I have code that contstructs a HttpPost request like the following...
public LoginForm apa;
....
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
HttpParams httpparams = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(httpparams, schemeRegistry);
HttpClient httpclient = new DefaultHttpClient(mgr, httpparams);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(String i : apa.getParams().keySet()){
nameValuePairs.add(new BasicNameValuePair(i, apa.getParams().get(i)));
}
List<NameValuePair> cookies = new ArrayList<NameValuePair>();
StringBuilder sb = new StringBuilder();
for(String i : apa.getCookies().keySet()){
sb.append(i);
sb.append("=");
sb.append(apa.getCookies().get(i));
sb.append(";");
}
// Trying to remove last ;
String cookie = sb.toString();
cookie = cookie.substring(0, cookie.length()-1);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httppost.setHeader("Cookie", cookie);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(EntityUtils.toString(response.getEntity()));
It isn't logging in quite as I would expect so is there a way to output the entire request (headers and all) to match it up with the one I see in my Chrome Dev Tools? Am I over thinking this? Is there a form login library for Android or Java in general? Do I need content-length added?
Printing the headers is easy - you can list them using method getAllHeaders.
If you need to print HttpEntity, you can use method writeTo to write whole entity into ByteArrayOutputStream and create a String using toString.
I'm trying to post combination of string to my backend server. How can I achieve that using BasicNameValuePair. Here are some code which I was trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost("API HERE");
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));
I want to send username and password like:
username=USER&password=PWD
How to achieve the successful post to the server.
Help will be appreciated.
The following is what I use for all of my POST variables:
HttpParams httpParams = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost;
httpPost = new HttpPost(Net_URL + Net_Get);
httpPost.setEntity(new UrlEncodedFormEntity(/*Name Value Pairs*/));
HttpResponse response = httpClient.execute(httpPost);
As a side suggestion, I would first do an some sort of encryption of a users password before sending it over the network, I have seen many who do not do this ^.^
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());